Use a byte-for-byte comparison when the question is whether two local files have identical contents. The same filename or size gives you a clue, but a change from 12 to 13 takes up the same space. A binary comparison can find that change immediately. Use a SHA-256 digest when you need a compact fingerprint that can be calculated separately and compared later.
Decide whether identity or meaning matters
If you want to confirm that a copy preserved every byte, open the two files in binary mode. Windows and Unix line endings can make two text files differ even when they look the same in an editor. A text encoding marker can do the same. For checking copies and packaged fixtures, these distinctions matter. A binary comparison preserves them.
If you want to know whether two CSV exports describe the same orders, a raw comparison answers a different question. A new column order or different quoting can change the bytes while leaving the records equivalent under a defined interpretation. Read the files with the Python CSV guide and compare the fields that matter to you. Decide whether row order, duplicate rows, and empty fields count before comparing business data.
Make three files with controlled contents
Place the example files beside the script in one folder. Make source.txt contain the line units=12 and create an exact copy named copy.txt. In a third file namedchanged.txt, write units=13 with the same encoding and newline settings. Using the same editor for both lines makes it easier to keep the file sizes equal. If you are checking from a shell, make the exact copy with its usual copy command before editing the separate third file.
Save this as compare_files.py. It reads bounded chunks, so it does not need to place both complete files in memory. Usable file paths are passed as command-line arguments. If a path contains spaces, pass it as one quoted argument in your shell.
import argparse
from pathlib import Path
CHUNK_SIZE = 256 * 1024
def same_bytes(left: Path, right: Path) -> bool:
with left.open("rb") as first, right.open("rb") as second:
while True:
chunk = first.read(CHUNK_SIZE)
other = second.read(CHUNK_SIZE)
if chunk != other:
return False
if not chunk:
return True
parser = argparse.ArgumentParser(description="Compare two files by content.")
parser.add_argument("left", type=Path)
parser.add_argument("right", type=Path)
args = parser.parse_args()
try:
equal = same_bytes(args.left, args.right)
except OSError as error:
parser.exit(2, f"Could not compare files: {error}\n")
print("Identical bytes." if equal else "Different bytes.")
raise SystemExit(0 if equal else 1)
Run the first command below from the example folder. It should print Identical bytes. The second should print Different bytes. Even though the third file has the same length, the value has changed.
python compare_files.py source.txt copy.txt
python compare_files.py source.txt changed.txt

Follow the decision at the end of each read
Each loop tries to read one piece from each regular file. If the chunks differ, the comparison is already settled. If both pieces are empty bytes, both files have reached the end together, and the function returns true. If one piece is empty and the other contains bytes, the inequality is detected first. That order also handles two empty files correctly: they match because both streams reach the end immediately.
The chunk size controls how much data the program handles at one time. A larger buffer does not change the meaning of identical. For modest files, use the default in the example and check the results first. For a repeated comparison of large files, measure performance on the storage where the task actually runs. A drive, network mount, and cached local folder can behave quite differently.

This example reads regular files that are stable while you compare them. If another process is writing to one of them, the chunks might reflect different moments. Wait for the producer to close and finish the output, or compare stable copies made at an appropriate point in the workflow. A successful result gives you evidence about what the program read during that run.
Choose when a standard library shortcut is enough
Python offers filecmp.cmp(left, right, shallow=False) for a shorter comparison. Pass shallow=False when you need it to compare contents even when the metadata looks similar. The default shallow behaviour can treat matching stat signatures as sufficient. The module also caches results. If you are repeatedly editing and comparing the same paths within one process, read the cache documentation and clear the cache where necessary, or use the explicit read loop above. Python filecmp documentation
A quick test is to open two readable files with the same length and change one character in one of them. Compare their names and sizes, then run the program. You can also append a line to one copy and repeat the run to check the different-length case. When a one-off comparison gives a surprise, those two changes help you see what the method measures.
Use a SHA-256 digest if the files are in different places
One practical use for a digest is recording a fingerprint for an export and verifying it on another machine later. With two local files and a simple yes-or-no question, the read loop can stop after the first mismatch. Digesting both files requires reading all of both. The trade-off is that a recorded digest can be passed around without copying the original file alongside it.
The following small script prints SHA-256 digests for whichever local files you name. It useshashlib.file_digest(), available from Python 3.11. Save it as print_digests.py and give it the same example paths.
import argparse
from hashlib import file_digest
from pathlib import Path
parser = argparse.ArgumentParser(description="Print SHA-256 file digests.")
parser.add_argument("files", type=Path, nargs="+")
args = parser.parse_args()
for path in args.files:
try:
with path.open("rb") as source:
value = file_digest(source, "sha256").hexdigest()
except OSError as error:
parser.exit(2, f"Could not read {path}: {error}\n")
print(f"{value} {path}")
Run python print_digests.py source.txt copy.txt changed.txt. The first two digest strings should match, and the third should differ. Record the algorithm alongside a digest when you save it. A string generated with SHA-256 is only directly comparable to another SHA-256 digest of the intended bytes. Python hashlib documentation

A digest can flag a difference from a recorded reference. Connecting the reference to a trusted source is a separate decision. If the file and the digest came from the same editable location, the digest alone does not establish who published either of them. For checking your own export later, keep the original record somewhere you can identify reliably.
Diagnose a surprising result before deleting or replacing files
If two text files look alike but the script says they differ, check the encoding, line endings, and final newline. A text editor can hide these differences, especially if it automatically converts them when saving. Work on a copy so the original remains available for diagnosis. A comparison tool that shows byte offsets or a text diff with whitespace enabled can help you locate the change after this script answers the equality question.
If the program cannot read one of the inputs, look at the filename and the folder from which you ran it. A missing file, a directory supplied in place of a file, or an access error is a failed comparison. The example returns exit status two in these cases. Status zero means matching bytes and status one means a difference. A script that calls this tool can use those distinct results to decide whether to continue, report a mismatch, or investigate a problem.
Use the smallest useful verification for a folder of exports
If your real job arrives as a batch of files, decide what makes a pair first. Two folders may have files that share a basename but represent different report dates. Confirm the filename convention or use a small manifest that names each expected source and destination. Check the pair you intended to compare before working on performance. Exact bytes give a precise result only for the inputs you actually selected.
For a handful of files, keep a report with one row per planned comparison. Note matching files, differing files, and reads that failed. If a destination file disappeared between checking it and reading it, capture that failure explicitly. This approach helps when somebody wants a summary of a transfer later and needs to know whether a pair was compared or skipped.
If two folders disagree, avoid immediately putting a source file in place of every destination. There may be a changed configuration or a new export at the destination. Use the diagnostic result to select a pair for inspection and decide which version is authoritative. The comparison itself opens both files for reading only.
Read an encoding or line-ending mismatch as a separate case
Suppose the raw comparison reports a difference and a text diff shows no change in the visible words. One possibility is that the source uses a line feed while the destination uses carriage return plus line feed. Another is that one file begins with a UTF-8 signature, and the other does not. Read small samples with a tool capable of showing whitespace or raw bytes. The difference can be real even when it would have little effect on another text reader.
If the two files are meant to remain exact archival copies, the mismatch matters. If they are meant to contain equivalent human-readable text across operating systems, document the permitted differences before applying normalisation. A second, deliberately text-aware comparison can answer that question. Keep the binary check available so you can see whether the underlying bytes changed.
Check one difference beyond the first read
The three-file example demonstrates a same-length edit within a small chunk. To exercise the loop, make both files larger than the buffer, duplicate one of them, and alter a byte near its end in the separate copy. The first reads should agree while a later one differs. This catches a common testing blind spot where a program accidentally compares only the first part. Use disposable files and record the fixture size so the person repeating the test knows it crossed the buffer.
Also try a command with one missing input. A shell script should distinguish the missing-input status from a changed file. That separation keeps your copy checks honest when another step writes to a different folder or leaves a file incomplete. You should be able to tell whether a mismatch was established or the attempted comparison stopped early.
For a copy check that will be repeated, save a tiny set of known examples next to the command you plan to use. One exact copy and one same-size change are enough to catch the most common mix-up between metadata and content. Add an empty pair if your export process can legitimately create empty files. When the examples behave as expected, you can run the same comparison on the actual files and know what the result means.
