WindowsError:[错误2]系统找不到指定的文件,无法在Python中解析
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了WindowsError:[错误2]系统找不到指定的文件,无法在Python中解析,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2632字,纯文字阅读大概需要4分钟。
内容图文
我已经制作了一个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中解析全部内容,希望文章能够帮你解决WindowsError:[错误2]系统找不到指定的文件,无法在Python中解析所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。