我试图通过删除其基本名称中的最后四个字符来重命名子目录中存储的许多文件。我通常使用glob.glob()找到并重命名文件一个目录 using:
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)
The 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
我该如何解决这个问题?