WindowsError:[错误2]系统找不到指定的文件,无法在Python中解析

我已经制作了一个Python程序,该程序将清除下载的torrent文件文件夹中存在的不必要名称,以便我可以轻松地将其上传到我的无限Google Drive存储帐户中.但是,它给了我:WindowsError:[错误2]在经过一定的迭代次数后,系...

我已经制作了一个Python程序,该程序将清除下载的torrent文件文件夹中存在的不必要名称,以便我可以轻松地将其上传到我的无限Google Drive存储帐户中.

但是,它给了我:WindowsError:[错误2]在经过一定的迭代次数后,系统找不到指定的文件.如果我再次运行该程序,则对于某些迭代它仍然可以正常工作,然后弹出相同的错误.

请注意,我已经使用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的工作方式,这可能是子目录的问题,即第一个具有子目录的迭代之后的下一个迭代的路径. 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'])

本文标题为:WindowsError:[错误2]系统找不到指定的文件,无法在Python中解析

基础教程推荐