Are two files equal in contents and metadata? It is sometimes useful to determine if a file is the same as another file. With filecmp
, a Python module, this is possible.
Although it would be possible to implement the logic from filecmp
in each program, filecmp
offers convenient pre-built functionality. This reduces the amount of code you need to write.
This program creates 2 separate files and populates them with some data. It then compares the files with the filecmp.cmp
method.
open()
calls to create two files (or rewrite the contents of any existing files with those names). We write some data to each.filecmp.cmp
. This returns true, as the contents are equal.filecmp.cmp
again, we get a False result as the files now have different contents.import filecmp f1 = "example.txt" f2 = "example2.txt" # Step 1: create the 2 files with identical text. with open(f1, "w") as f: f.write("Some example text") with open(f2, "w") as f: f.write("Some example text") # Step 2: compare the files. result = filecmp.cmp(f1, f2, shallow=True) print(result) # Step 3: modify the second file. with open(f2, "w") as f: f.write("Different text") # Step 4: compare the files again. result = filecmp.cmp(f1, f2, shallow=True) print(result)True False
With the filecmp
module, we have some useful methods like cmp and cmpfiles—these methods compare the metadata and (if necessary) the contents of files.