Coming from another language than Python, I would like to see if my code is "pythonic" enough and follows good practices.
It compares two directories, showing all files that are in one and not in the other. Moreover, you can add up to two options:
- a to also compare the content of the files
- s to save the results into a file
Note: this is in Python 2.7, and I don't have access to argparse
.
import filecmp
import os.path
import sys
def print_help():
print "Use : python cmp_dir.py <dir_1> <dir_2> [-a] [-s <file>]"
print "dir_1 and dir_2 : directories to compare"
print "-a : also compare data inside files"
print "-s : save results inside <file>"
sys.exit()
def show_diff_in_dir(dir_name, list_diff, file_to_save_results):
msg = "files or subdirs only in %s : %s " % (dir_name, list_diff)
if file_to_save_results:
file_to_save_results.write(msg + "\n")
else:
print msg
def show_diff_in_files(dir_name, diff_files, file_to_save_results):
msg = "different files in %s : %s " % (dir_name, diff_files)
if file_to_save_results:
file_to_save_results.write(msg + "\n")
else:
print msg
def compare_dir_trees(dir1, dir2, compare_file_data, file_to_save_results):
dirs_cmp = filecmp.dircmp(dir1, dir2)
if dirs_cmp.left_only:
show_diff_in_dir(dir1, dirs_cmp.left_only, file_to_save_results)
if dirs_cmp.right_only:
show_diff_in_dir(dir2, dirs_cmp.right_only, file_to_save_results)
if compare_file_data and dirs_cmp.diff_files:
show_diff_in_files(dir1, dirs_cmp.diff_files, file_to_save_results)
for common_dir in dirs_cmp.common_dir:
new_dir1 = os.path.join(dir1, common_dir)
new_dir2 = os.path.join(dir2, common_dir)
compare_dir_trees(new_dir1, new_dir2, compare_file_data, file_to_save_results)
if __name__ == "__main__":
compare_file_data = False
file_to_save_results = None
if len(sys.argv) < 3:
print_help()
else:
dir_a = sys.argv[1]
dir_b = sys.argv[2]
if len(sys.argv) == 4:
if sys.argv[3] == "-a":
compare_file_data = True
else:
print_help()
elif len(sys.argv) == 5:
if sys.argv[3] == "-s":
file_to_save_results = open(sys.argv[4], "w")
else:
print_help()
elif len(sys.argv) == 6:
if sys.argv[3] == "-a" and sys.argv[4] == "-s":
compare_file_data = True
file_to_save_results = open(sys.argv[5], "w")
elif sys.argv[5] == "-a" and sys.argv[3] == "-s":
compare_file_data = True
file_to_save_results = open(sys.argv[4], "w")
else:
print_help()
elif len(sys.argv) > 6:
print_help()
print "Compare dirs %s and %s" % (dir_a, dir_b)
print "Start compare"
compare_dir_trees(dir_a, dir_b, compare_file_data, file_to_save_results)
if file_to_save_results:
file_to_save_results.close()
print "End compare"