Filecmp. 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.
Example. This program creates 2 separate files and populates them with some data. It then compares the files with the filecmp.cmp method.
Step 1 We use 2 open() calls to create two files (or rewrite the contents of any existing files with those names). We write some data to each.
Step 2 We compare the files with filecmp.cmp. This returns true, as the contents are equal.
Step 3 We modify the contents of the second file and write some text that is different to the file.
Step 4 When we call 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
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.