Python 如何使用os.walk()重命名文件?
我试图通过删除basename中的最后四个字符来重命名存储在子目录中的许多文件。我通常使用以下方法查找并重命名一个目录中的文件:Python 如何使用os.walk()重命名文件?,python,file-rename,os.walk,Python,File Rename,Os.walk,我试图通过删除basename中的最后四个字符来重命名存储在子目录中的许多文件。我通常使用以下方法查找并重命名一个目录中的文件: 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 = "".joi
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)
但现在我想在所有子目录中重复上述内容。我尝试使用:
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
回溯(最近一次呼叫最后一次):
文件“”,第7行,在
WindowsError:[错误2]系统找不到指定的文件
如何解决此问题?您必须将文件的完整路径传递给。返回的
元组的第一项是当前路径,因此只需将其与文件名组合即可:
import os
for path, dirs, files in os.walk("./data"):
for file in files:
pieces = list(os.path.splitext(file))
pieces[0] = pieces[0][:-4]
newFile = "".join(pieces)
os.rename(os.path.join(path, file), os.path.join(path, newFile))
您必须将文件的完整路径传递给。返回的元组的第一项是当前路径,因此只需将其与文件名组合即可:
import os
for path, dirs, files in os.walk("./data"):
for file in files:
pieces = list(os.path.splitext(file))
pieces[0] = pieces[0][:-4]
newFile = "".join(pieces)
os.rename(os.path.join(path, file), os.path.join(path, newFile))
我相信你应该在os.raname上传递文件的完整路径,因为你的文件与walk不在同一目录下…@RafaelRodrigoDeSouza-谢谢,正如niemmi的答案=)所描述的那样,您是正确的。我认为您应该在os.raname上传递文件的完整路径,因为您的路径与walk不在同一目录中…@RafaelRodrigoDeSouza-谢谢,您是正确的,正如niemmi的答案=)完美!谢谢你的回答:)太好了!谢谢你的回答:)