- 1 year ago
comparing the names of files (of different extensions) in two directories and removing the files which names are not in both directories
To compare the names of files in two directories, regardless of their file extensions, and remove the files whose names are not present in both directories, you can use the following Python code:
pythonimport os
def compare_directories(directory1, directory2):
files1 = set(os.listdir(directory1))
files2 = set(os.listdir(directory2))
common_files = files1.intersection(files2)
for file in files1 - common_files:
file_path = os.path.join(directory1, file)
os.remove(file_path)
print(f"Removed file: {file_path}")
for file in files2 - common_files:
file_path = os.path.join(directory2, file)
os.remove(file_path)
print(f"Removed file: {file_path}")
# Example usage
directory1 = '/path/to/directory1'
directory2 = '/path/to/directory2'
compare_directories(directory1, directory2)
In this example, the compare_directories
function takes two directory paths as input. It retrieves the list of files in each directory using os.listdir
, converts them to sets, and finds the common files using the intersection
method.
Then, it iterates over the files that are not common between the two directories and removes them using os.remove
. The file paths are constructed using os.path.join
.
Replace '/path/to/directory1'
and '/path/to/directory2'
with the actual paths of the directories you want to compare and remove files from.
Note: Please exercise caution when running this code, as it permanently removes files from the specified directories. Make sure to have appropriate backups of your files before performing any destructive operations.
Also, keep in mind that this code only compares file names and does not compare the file contents. If you need to compare file contents, you would need to consider additional logic to check for equality between files based on their contents.