2016-02-28 128 views
3
解决

我已经做了Python程序,将清理目前的不必要的名字在我下载的种子文件+文件夹,这样我就可以把它上传到我的无限Google云端硬盘存储帐户没有太多麻烦。WindowsError:[错误2]系统找不到指定的文件,也不能在Python

然而,它给我的:WindowsError: [Error 2] The system cannot find the file specified一定数量的迭代之后。 如果我再次运行程序,它在某些迭代中可以正常工作,然后弹出相同的错误。

请注意,我已采取预防措施,使用os.path.join来避免此错误,但它不断出现。由于这个错误,我必须在选定的文件夹/驱动器上运行数十次程序。

这里是我的程序:

import os 
terms = ("-LOL[ettv]" #Other terms removed 
) 
#print terms[0] 
p = "E:\TV Series" 
for (path,dir,files) in os.walk(p): 
    for name in terms: 
     for i in files: 
      if name in i: 
       print i 
       fn,_,sn = i.rpartition(name) 
       os.rename(os.path.join(path, i), os.path.join(path, fn+sn)) 
     for i in dir: 
      if name in i: 
       print i 
       fn,_,sn = i.rpartition(name) 
       os.rename(os.path.join(path, i), os.path.join(path, fn+sn)) 

和错误回溯:

Traceback (most recent call last): 
File "E:\abcd.py", line 22, in <module> 
os.rename(os.path.join(path, i), os.path.join(path, fn+sn)) 
WindowsError: [Error 2] The system cannot find the file specified 

回答

3

也许它与子目录的问题,由于道路os.walk作品,分别path对下一次迭代先用后子目录。 os.walk集子目录的名字就在当前目录下它的第一次迭代进一步的迭代参观...

例如,在第一次调用os.walk你:

('.', ['dir1', 'dir2'], ['file1', 'file2']) 

现在重命名这些文件(该工程确定),并且您将其重命名为:'dir1''dirA''dir2''dirB'

os.walk下一个迭代,您可以:

('dir1', ['subdir1-2', 'subdir1-2'], ['file1-1', 'file1-2']) 

会发生什么,在这里是没有'dir1'了,因为它已经被重命名的文件系统,但os.walk还记得它的老名称列表里面,并给你。现在,当您尝试重命名'file1-1'时,您会要求输入'dir1/file1-1',但在文件系统上,它实际上是'dirA/file1-1',您会收到错误消息。

为了解决这个问题,您需要更改所使用的os.walk进一步迭代列表,例如值在你的代码:

for (path, dir, files) in os.walk(p): 
    for name in terms: 
     for i in files: 
      if name in i: 
       print i 
       fn, _, sn = i.rpartition(name) 
       os.rename(os.path.join(path, i), os.path.join(path, fn+sn)) 
     for i in dir: 
      if name in i: 
       print i 
       fn, _, sn = i.rpartition(name) 
       os.rename(os.path.join(path, i), os.path.join(path, fn+sn)) 
       #here remove the old name and put a new name in the list 
       #this will break the order of subdirs, but it doesn't 
       #break the general algorithm, though if you need to keep 
       #the order use '.index()' and '.insert()'. 
       dirs.remove(i) 
       dirs.append(fn+sn) 

这应该做的伎俩在上述方案中所述,会导致...

在第一次调用os.walk

('.', ['dir1', 'dir2'], ['file1', 'file2']) 

现更名:'dir1''dirA''dir2''dirB'并更改上面显示的列表...现在,在下一次迭代os.walk时,它应该是:

('dirA', ['subdir1-2', 'subdir1-2'], ['file1-1', 'file1-2']) 
+0

是的!这是我期望的答案。在猜测问题(这是一个艰难的部分)之后,我已经在一小时前解决了它,解决方案并没有花费太多时间,我所做的只是使用'enumerate'并编辑'dir'重命名目录的索引。 –

+0

顺便说一句,在我猜错了之后,我在[这里]发布了另一个问题(http://stackoverflow.com/questions/35683291/how-to-update-current-directories-in-the-list-of -os-walk-while-renaming-it-in-re),在那里我用一个答案更新帖子。 –

相关问题