2016-02-28 111 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),在那裏我用一個答案更新帖子。 –

相關問題