Python递归文件重命名

时间:2015-07-14 10:48:05

标签: python recursion path rename errno

我是python的新手,我正在尝试创建一个python脚本,它能够递归地重命名包含子目录的目录中的每个文件。但每次我运行脚本时我都会收到错误

OSError:[Errno 2]没有这样的文件或目录

该目录包含一些文本文件和包含其他文件的文件夹。

有谁知道为什么会一直这样?

代码:

import os
path = "example path here"
new_filename= ""
i = 0

filenames = os.listdir(path) # is this line needed?
for dir,subdir,listfilename in os.walk(path):
    for filename in listfilename:
        i += 1
        new_filename = 'filename' + str(i)
        src = os.path.join(path, filename)
        dst = os.path.join(path, new_filename)
        os.rename(src, dst)

1 个答案:

答案 0 :(得分:3)

我相当肯定这个问题源于你加入通往"路径的新途径。变量而不是从#import .bar as bar # why not?!? #import .bar # shot in the dark import foobar.bar as bar # current solution 返回的当前目录。

walk

你应该阅读os.walk的文档,我不确定你完全理解它的作用?

另外,不要调用变量import os path = "example path here" new_filename= "" # This isn't C, we don't need to pre-declare a variable. i = 0 filenames = os.listdir(path) # is this line needed? # not that I can see, no for dir,subdir,listfilename in os.walk(path): for filename in listfilename: i += 1 new_filename = 'filename' + str(i) src = os.path.join(dir, filename) # NOTE CHANGE HERE dst = os.path.join(dir, new_filename) # AND HERE os.rename(src, dst) ,它会以相同的名称屏蔽内置函数。

另外,您也不需要在循环之外预先声明dir