【问题标题】:How to rename files using os.walk()?如何使用 os.walk() 重命名文件?
【发布时间】:2016-12-09 22:07:12
【问题描述】:

我正在尝试通过删除基本名称中的最后四个字符来重命名存储在子目录中的许多文件。我通常使用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.raname,因为你和 walk 不在同一个目录中......
  • @RafaelRodrigoDeSouza - 谢谢,你是正确的,正如 niemmi 的回答所描述的那样 =)

标签: python file-rename os.walk


【解决方案1】:

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

【讨论】:

  • 完美!谢谢你的回答:)
猜你喜欢
  • 1970-01-01
  • 2019-03-05
  • 2020-04-03
  • 2011-01-30
  • 2011-03-30
  • 2012-06-01
  • 2017-07-25
  • 1970-01-01
相关资源
最近更新 更多