- 1 year ago
Compare files in folders and delete non existent - part 2
Continuing from the previous response, if you want to compare files in two folders and delete the non-existent files in one folder based on the comparison, you can use the following Python code:
pythonimport os
def compare_and_delete_files(folder1, folder2):
files1 = set(os.listdir(folder1))
files2 = set(os.listdir(folder2))
non_existent_files = files1 - files2
for file in non_existent_files:
file_path = os.path.join(folder1, file)
os.remove(file_path)
print(f"Deleted: {file_path}")
# Example usage
folder1 = "/path/to/folder1"
folder2 = "/path/to/folder2"
compare_and_delete_files(folder1, folder2)
In the code above, the compare_and_delete_files
function takes two folder paths as input. It obtains the lists of files in each folder using os.listdir
and converts them to sets for efficient comparison.
The function then calculates the set difference between files1
and files2
to find the files that exist in folder1
but not in folder2
.
Finally, it iterates over the non-existent files and deletes them using os.remove
, providing the absolute file path. The function also prints a message for each file that is deleted.
You can replace folder1
and folder2
with the actual paths to the folders you want to compare and delete files from.
Please exercise caution when deleting files, as this operation is irreversible. It is recommended to test the code on a sample or backup data before performing it on your actual files.