[英]How to check and delete files that are not same in two different directories in python?
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? 谁能告诉我我在哪里犯错了?
You can use set to check efficiently for the duplicates. 您可以使用set来有效地检查重复项。
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.