栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

WindowsError:[错误2]系统找不到指定的文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

WindowsError:[错误2]系统找不到指定的文件

我怀疑您的子目录可能有问题。

如果您的目录包含文件“

a
”,“
b
”和子目录“
dir
”,分别包含文件“
sub+1
”和“
sub+2
”,则对的调用
os.walk()
将产生以下值:

(('.',), ('dir',), ('a', 'b'))(('dir',), (,), ('sub+1', 'sub+2'))

当你处理第二元组,你会调用

rename()
'sub+1', 'sub_1'
作为参数,当你想要的是
'dirsub+1','dirsub_1'

要解决此问题,请将代码中的循环更改为:

for root, dirs, filenames in os.walk(folder):    for filename in filenames:        filename = os.path.join(root, filename)        ... process file here

在执行任何操作之前,它将使用文件名连接目录。

编辑:

我认为以上是正确的答案,但并非完全正确的理由。

假设您

File+1
的目录中有一个文件“ ”,
os.walk()
将返回

("C:/documents and Settings/DuffA/Bureaublad/Johan/10G304655_1/", (,), ("File+1",))

除非您在

10G304655_1
目录中,否则在调用时
rename()
File+1
将不在 当前 目录中找到文件“ ”
,因为该目录与
os.walk()
正在查找的目录不同。通过对
os.path.join()
yuo的调用,告诉重命名为look在正确的目录中。

编辑2

所需代码的示例可能是:

import os# Use a raw string, to reduce errors with  characters.folder = r"C:documents and SettingsDuffABureaubladJohan10G304655_1"old = '+'new = '_'for root, dirs, filenames in os.walk(folder): for filename in filenames:    if old in filename: # If a '+' in the filename      filename = os.path.join(root, filename) # Get the absolute path to the file.      print (filename)      os.rename(filename, filename.replace(old,new)) # Rename the file


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/661017.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号