簡體   English   中英

WindowsError:[錯誤2]系統找不到指定的文件,無法在Python中解析

[英]WindowsError: [Error 2] The system cannot find the file specified, cannot resolve in Python

我已經制作了一個Python程序,它將清除我下載的torrent文件+文件夾中不必要的名稱,這樣我就可以毫不費力地將它上傳到我無限制的Google雲端硬盤存儲帳戶。

但是,它給出了: WindowsError: [Error 2] The system cannot find the file specified在一定次數的迭代后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

可能是由於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'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM