Have you heard about filecmp and how to use it for a quick way to compare files in Python? Sometimes when writing a unit test in Python, you need to assert that two files are the same. A naive solution would be to loop both files and the lines of the files into lists and compare both lists (assuming that both files are plain text).
Luckily, Python has a native library that can do the job much easier and cleaner. when trying to run a simple file comparison.
How to use it
You can simply use python filecmp to do the job. Please see the example below:
# Please assume that 'file1.txt' is different than 'file2.txt'
>>> import filecmp
>>> filecmp.cmp('file1.txt', 'file1.txt')
True
>>> filecmp.cmp('file1.txt', 'file2.txt')
False
More Resources
Here are three of my favorite Python Books in case you want to learn more about it.
- Python Cookbook, Third Edition by David Beazley and Brian K. Jones
- Learning Python, 5th Edition Fifth Edition by Mark Lutz
- Python Pocket Reference: Python In Your Pocket by Mark Lutz