如何使用os.walk()重命名文件?

时间:2016-12-09 13:11:25

标签: python file-rename os.walk

我试图通过删除其基本名称中的最后四个字符来重命名存储在子目录中的多个文件。我通常使用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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您必须将文件的完整路径传递给os.renameos.walk返回的tuple的第一项是当前路径,因此只需使用os.path.join将其与文件名组合:

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))