如何使用os.walk()重命名文件? [英] How to rename files using os.walk()?

查看:153
本文介绍了如何使用os.walk()重命名文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过删除其基名中的最后四个字符来重命名子目录中存储的许多文件.我通常使用 glob.glob() 在其中定位和重命名文件一个目录使用:

I'm trying to rename a number of files stored within subdirectories by removing the last four characters in their basename. I normally use glob.glob() to locate and rename files in one directory 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() :

But now I want to repeat the above in all subdirectories. I tried using 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)返回以下错误:


The print statement correctly prints the original and the new filenames that I am looking for but os.rename(file,newFile) returns the following error:

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

我该如何解决?

推荐答案

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

You have to pass the full path of the file to os.rename. First item of the tuple returned by os.walk is the current path so just use os.path.join to combine it with file name:

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

这篇关于如何使用os.walk()重命名文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆