Create a CSV list of files in a folder
Scan subfolders and record file paths, extensions, sizes, and modification times in a table. Start with 4 small example files while keeping the originals and existing results intact.
Check the result of a file copy by comparing hashes of the file bytes rather than relying only on names or sizes.
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
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.
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.
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.
python example.pyA 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.
| Key | Meaning |
|---|---|
| algorithm | The hash algorithm used: SHA-256 |
| files | The names of the two files compared |
| sha256 | The 64-character hash string for each file |
| same_sha256 | true 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.
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.
"""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
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.
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.
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.
2026-09-19 · Windows 11 · CPython 3.12.14 · Standard library
Includes code, input data, and instructions. Extract the ZIP and read README.txt first.
Download example ZIPExample 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.
The explanations and examples were written for this site. See the official sources below for the related behavior and concepts.