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

2023-12-12

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

我该如何解决这个问题?


您必须将文件的完整路径传递给os.rename。第一项的tuple由返回os.walk是当前路径,所以只需使用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))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 os.walk() 重命名文件? 的相关文章

随机推荐