简体   繁体   English

如何检查和删除python中两个不同目录中不相同的文件?

[英]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.

相关问题 如何检查名称相同但扩展名不同的目录中的文件 - How to check files in different directories with same name but different extensions 如何递归删除两个目录中的不同文件 - How to recursively remove different files in two directories 如何使用Meld比较不同目录中的两个相同名称文件(不提供其路径)? - How to compare two same name files in different directories using meld (without giving their path)? 如何使用单个命令删除linux中不同目录中的文件 - How to delete files in different directories in linux with a single command 如何从多个目录中提取多个文件,而不同目录中的不同文件可能具有相同的名称 - how to scp multiple files from multiple directories, while different files in different directories may have the same name 在两个主目录中查找具有相同名称和子目录但内容不同的文件 - Finding the Files with the Same Name and Sub-Directories But Different Contents in Two Main Directories 如何使用find重命名具有相同名称的不同目录中的文件 - How to rename files in different directories with the same name using find 删除除两个特定目录之外的所有文件/目录 - Delete all files/directories except two specific directories 检查两个目录是否在haskell中的同一文件系统上 - Check if two directories are on the same filesystem in haskell 比较Linux中两个不同目录中的文件 - Compare files in two different directories in Linux
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM