gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:02:52 35 4
gpt4 key购买 nike

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

我该如何解决这个问题?

最佳答案

您必须将文件的完整路径传递给 os.rename . 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))

关于python - 如何使用 os.walk() 重命名文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41061291/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com