Reputation: 793
I've two folder and i want to keep the files that are same in both the folders. So now if want to delete the files that are not present in both the folders, with "the same" using filenames.
I'm trying this one but it doesn't seems to be working out.
dir1 = os.listdir('/home/Desktop/computed_1d/')
dir2 = os.listdir('/home/Desktop/computed_2d_blaze/')
for filename in dir1:
try:
for filen in dir2:
if filename != filen:
os.remove(filename)
except:
pass
Can anyone tell me where I'm making the mistake?
Upvotes: 0
Views: 44
Reputation: 11929
You can use set to check efficiently for the duplicates.
dir1 = os.listdir(path1)
dir2 = os.listdir(path2)
duplicates = set(dir1) & set(dir2)
# delete from dir1
for file in dir1:
if file not in duplicates:
os.remove(os.path.join(path1,file))
# delete from dir2
for file in dir2:
if file not in duplicates:
os.remove(os.path.join(path2,file))
Upvotes: 1