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

How to rename files using 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) returns 出现以下错误:

Traceback (most recent call last):
  File "<input>", line 7, in <module>
WindowsError: [Error 2] The system cannot find the file specified

我该如何解决这个问题?

您必须将文件的完整路径传递给 os.rename. First item of the tuple returned by os.walk is the current path so just use 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))