Python的循环从当前文件

问题描述:

我正在尝试通过目录中的文件,找到重复并删除它们。我在目录中有29 000个文件,所以做一个暴力破解将需要超过一天的时间。Python的循环从当前文件

我是如下的文件名:

“some_file_name” “一些文件名称”

那么一个名字有下划线,另一种有破折号,有时他们是2个或三个点分开。

那么,如何我在外环在目录中的位置,我的内循环的开始,使之只检查接下来的10?

这里是我的蛮力代码:

import glob, os 
os.chdir("C:/Dir/dir") 

for file in glob.glob("*"): 
    temp = file 
    temp = temp.replace("-", " ") 
    temp = temp.replace("_", " ") 

#How do I start this loop where file is currently at and continue for the next 10 files 
for file2 in glob.glob("*"): 
    temp2 = file2 
    temp2 = temp2.replace("-", " ") 
    temp2 = temp2.replace("_", " ") 
    if temp == temp2: 
     os.remove(file2) 
+0

你想找到的内容或类似的重复姓名? – Tomalak

+0

而不是循环两次,你尝试过使用的数据结构(一组或列表),以确保您已经访问过的文件名的轨道(temp1中和TEMP2)?这样你只需要在每个文件上循环一次。 – pills

从我从你的问题明白了,你想从目录中删除类似命名的文件。我认为你的方法(“看看接下来的10个文件名左右”)太不精确和太复杂。

条件是,当文件some_file_name和文件some-file-name存在时,删除其中的一个。

这可以通过建立一个文件名列表,并为每个表项的检查很容易做到,如果用下划线而不是短横线的文件名也存在,如果有,将其删除。

下面使用set来做到这一点,因为集具有非常好的查找​​特性,即some_value in some_set比列表更快。它还避免了过多的文件存在检查(如调用os.path.isfile(file)),因为我们已经知道构建集合时存在的所有文件。

import glob, os 

filenames = {file for file in glob.glob(r"C:\Dir\dir\*")} 

for file in filenames: 
    delete_candidate = file.replace("-", "_") 
    if delete_candidate != file and delete_candidate in filenames: 
     os.remove(delete_candidate) 
     print("deleted " + delete_candidate) 

{x for x in iterable}一套理解,它构建从值的列表中设置。它的工作原理与列表解析相似。

+0

使用'{}'的一套理解,您创建了一个发电机 – Uriel

+0

D'哦。当然。 – Tomalak

+0

谢谢,我现在感觉有点傻。这实际上是一个非常简单的解决方案,尽管如此,谢谢,它的工作原理! – user3918910

你可以使用一本字典,把“简单的名字”(不_或 - )为重点,所有的真实文件名作为值:

import glob, os 

def extendDictValue(dDict, sKey, uValue): 
    if sKey in dDict: 
     dDict[sKey].append(uValue) 
    else: 
     dDict[sKey] = [uValue] 


os.chdir("C:/Dir/dir") 
filenames_dict = {} 
for filename in glob.glob("*"): 
    simple_name = filename.replace("-", " ").replace("_", " ") 
    extendDictValue(filenames_dict, simple_name, filename) 

for simple_name, filenames in filenames_dict.items(): 
    if len(filenames) > 1: 
     filenames.pop(0) 
     for filename in filenames: 
      os.remove(filename)