''' --------------COMPARE TWO FOLDERS---------------------------------------------- Ref: askubuntu.com/questions/421712/comparing-the-contents-of-two-directories Syntax: python3 Py/compareFolders.py ../folder1 ../folder2. The first folder is called source folder and second is called target folder. The aim is to modify the code for in-place copy/deletion of files in target folder. It doesn't compare contents of the files. Also it doesn't travel inside sub- directories which are missing in one of the directories. ''' #!/usr/bin/env python3 import os, sys, shutil def compare_dirs(d1: "Source directory name", d2: "Target directory name"): def print_local(t, a, msg): print(t, 'DIR--- ' if a[2] else 'FILE--', a[1], msg) # Ensure validity: check that both arguments are valid folder names for d in [d1,d2]: if not os.path.isdir(d): raise ValueError("not a directory: " + d) # Get relative path: array of file names for two folders # Create a List of Tuples (file_name, relative_path) l1 = [(x,os.path.join(d1,x)) for x in os.listdir(d1)] #print(l1) l2 = [(x,os.path.join(d2,x)) for x in os.listdir(d2)] # Determine type: directory or file? # Sort the tuples by adding Boolean for folders (True). The new list formed # are List of Tuples like (file_name, relative_path, True). They are sorted # in ascending older: files first and then folders l1 = sorted([(x,y,os.path.isdir(y)) for x,y in l1]) l2 = sorted([(x,y,os.path.isdir(y)) for x,y in l2]) #Set file counters to ZERO i1 = i2 = 0 common_dirs = [] while i1l2[i2][0]: #Files NOT found in source but in target print_local('\t\t',l2[i2],'\t-[added in target]') i2 = i2 + 1 while i1