Scripts and file automation

Check file contents by comparing SHA-256 hashes before and after copying

Check the result of a file copy by comparing hashes of the file bytes rather than relying only on names or sizes.

Show contents

This translation was generated by AI. Check the code, units, and numbers against the original. Native-speaker review has not yet been completed for each language. 한국어

Who this is forPython beginners who want to check whether a copied document has the same contents as the original

What you need
  • Have Python 3.12 or later ready. No additional packages are required.
  • Extract the ZIP into a new folder and keep example.py, original.txt, and copy.txt together.
  • Start by practicing with the included synthetic text files. Do not modify the files while they are being read.

01Compare bytes rather than file names

Files can have different contents even when their names and sizes are the same. SHA-256 reads the file bytes and computes a 64-character hexadecimal (base 16) string. The same bytes produce the same hash, so this can be used to check files before and after copying.

This exercise records in a report whether the two files have the same hash. It does not delete or replace files. A matching hash alone does not establish who created a file, whether it is an official distribution, or whether it is free of malware.

02Check the included files

original.txt and copy.txt contain the same single-line synthetic sentence. example.py locates and reads both files relative to its own location. The input paths remain the same even if the terminal’s current folder is different.

text
Worknote synthetic file comparison sample.

Even if the text looks the same on screen, differences in line endings, character encoding, or trailing spaces can produce different bytes and hashes. The files are compared as they are, without cleaning up the text or removing spaces.

03Run the first comparison

bash
python example.py

A new outputs folder and comparison.json file are created. The console value same_sha256=true means that the hashes of the two included files match. If outputs already exists, the program stops without overwriting it. To run the example again, extract a fresh copy into another folder.

04Values to check in the report

KeyMeaning
algorithmThe hash algorithm used: SHA-256
filesThe names of the two files compared
sha256The 64-character hash string for each file
same_sha256true if the two hashes match, false otherwise

The file names and hashes appear in the same order. The expected result for the included example is true. Creating a report file and obtaining a comparison result of true are different things, so check the value itself.

05How the code works and the full example

The digest function opens a file in binary read mode and updates the hash state by reading 1 MiB at a time. It does not load the entire file into memory at once. The results folder is created only after both input files have been read completely.

example.py
"""Compare two local synthetic files without changing them."""
import hashlib
import json
from pathlib import Path

BASE = Path(__file__).resolve().parent

def digest(path):
    value = hashlib.sha256()
    with path.open('rb') as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b''):
            value.update(chunk)
    return value.hexdigest()

def main():
    output = BASE / 'outputs'
    if output.exists():
        raise ValueError('outputs already exists; choose a fresh extraction folder.')
    left, right = BASE / 'original.txt', BASE / 'copy.txt'
    hashes = [digest(left), digest(right)]
    result = {'algorithm': 'SHA-256', 'files': [left.name, right.name],
              'sha256': hashes, 'same_sha256': hashes[0] == hashes[1]}
    output.mkdir(exist_ok=False)
    with (output / 'comparison.json').open('x', encoding='utf-8') as stream:
        json.dump(result, stream, indent=2)
        stream.write('\n')
    print('same_sha256=' + str(result['same_sha256']).lower())
    print('Created outputs/comparison.json')

if __name__ == '__main__':
    try:
        main()
    except (OSError, ValueError) as error:
        raise SystemExit(f'Stopped: {error}') from error

06Check whether different contents are detected

  1. Extract the ZIP again into a new folder to keep this run separate from the first result.
  2. In copy.txt, change sample to Sample and save the file.
  3. Run python example.py.
  4. Check that same_sha256=false and compare the two hashes.

Even if the character count stays the same, changing a single byte can reveal a difference in the hash comparison. This code does not determine whether a mismatch was caused by corruption or intentional editing.

07What to check when the program stops

If a file is missing or cannot be read, the program exits with a Stopped message. Check that the entire archive was extracted and that the file names are correct. If the error is caused by an existing outputs folder, extract a fresh copy into another folder and run it there.

If a disk write error occurs, an incomplete report may remain in the new outputs folder. Do not use the results until you have checked the completion message and the JSON contents.

08Limitations of hash comparison

Even cryptographic hashes have a theoretical possibility of collisions, so this is not described as a mathematically perfect proof of identity. This example is a small tool for routine copy checks. Verifying the authenticity of an official download requires a separate procedure to compare it against a hash or signature supplied by a trusted distributor.

Files changing while being read, network drive failures, access permissions, and performance with large files require separate checks. The code does not create snapshots of the input files or lock them.

Execution and verification record

2026-09-19 · Windows 11 · CPython 3.12.14 · Standard library

  • Confirmed true for identical files and false for different contents of the same length
  • Confirmed rejection of missing input and an existing output folder
  • Confirmed that the input SHA-256 hashes matched before and after execution
Verification limits
  • Concurrent modification, disk errors, and network drives were not verified.
  • Matching hashes do not guarantee the author’s identity or the file’s safety.

Site-wide writing and verification principles

Example files to run yourself

Includes code, input data, and instructions. Extract the ZIP and read README.txt first.

Download example ZIP

Example code, filenames, and input keys remain unchanged. Refer to the commands and checking steps in the translated article as well.

Practice materials created for this site · Keep your originals separately before running.

References

The explanations and examples were written for this site. See the official sources below for the related behavior and concepts.