【发布时间】:2016-12-09 22:07:12
【问题描述】:
我正在尝试通过删除基本名称中的最后四个字符来重命名存储在子目录中的许多文件。我通常使用glob.glob() 来定位和重命名一个目录中的文件:
import glob, os
for file in glob.glob("C:/Users/username/Desktop/Original data/" + "*.*"):
pieces = list(os.path.splitext(file))
pieces[0] = pieces[0][:-4]
newFile = "".join(pieces)
os.rename(file,newFile)
但现在我想在所有子目录中重复上述内容。我尝试使用os.walk():
import os
for subdir, dirs, files in os.walk("C:/Users/username/Desktop/Original data/"):
for file in files:
pieces = list(os.path.splitext(file))
pieces[0] = pieces[0][:-4]
newFile = "".join(pieces)
# print "Original filename: " + file, " || New filename: " + newFile
os.rename(file,newFile)
print 语句正确打印了我正在寻找的原始文件名和新文件名,但 os.rename(file,newFile) 返回以下错误:
Traceback (most recent call last):
File "<input>", line 7, in <module>
WindowsError: [Error 2] The system cannot find the file specified
我该如何解决这个问题?
【问题讨论】:
-
我相信你应该将文件的完整路径传递给 os.raname,因为你和 walk 不在同一个目录中......
-
@RafaelRodrigoDeSouza - 谢谢,你是正确的,正如 niemmi 的回答所描述的那样 =)
标签: python file-rename os.walk