Python。重命名子目录中的文件

Mac*_*jPL 1 python rename os.walk

您能否帮我修改以下脚本以更改子目录中的文件名。

def change():
    path = e.get()
    for filename in os.walk(path):
        for ele in filename:
            if type(ele) == type([]) and len(ele)!=0:
                for every_file in ele:

                    if every_file[0:6].isdigit():
                        number = every_file[0:6]
                        name = every_file[6:]
                        x = int(number)+y
                        newname = (str(x) + name)
                        os.rename(os.path.join(path, every_file), os.path.join(path, newname))
Run Code Online (Sandbox Code Playgroud)

boh*_*717 6

我不知道您对文件名有什么限制,因此我编写了一个通用脚本来向您展示如何在给定文件夹和所有子文件夹中更改它们的名称。

测试文件夹具有以下树结构:

~/test$ tree
.
??? bye.txt
??? hello.txt
??? subtest
?   ??? hey.txt
?   ??? lol.txt
?   ??? subsubtest
?       ??? good.txt
??? subtest2
    ??? bad.txt

3 directories, 6 files
Run Code Online (Sandbox Code Playgroud)

如您所见,所有文件都有.txt扩展名。

重命名所有这些的脚本如下:

import os


def main():
    path = "/path/toyour/folder"
    count = 1

    for root, dirs, files in os.walk(path):
        for i in files:
            os.rename(os.path.join(root, i), os.path.join(root, "changed" + str(count) + ".txt"))
            count += 1


if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

count 变量仅用于为每个文件使用不同的名称;也许你可以摆脱它。

执行脚本后,文件夹如下所示:

~/test$ tree
.
??? changed1.txt
??? changed2.txt
??? subtest
?   ??? changed4.txt
?   ??? changed5.txt
?   ??? subsubtest
?       ??? changed6.txt
??? subtest2
    ??? changed3.txt

3 directories, 6 files
Run Code Online (Sandbox Code Playgroud)

我认为,在你的代码的问题是,你不使用实际root的的os.walk功能。

希望这可以帮助。

  • 没门。我向您展示了如何作为一般程序执行此操作,现在轮到您了 ;) 我建议您仔细阅读有关 `os.walk` 函数的 Python 文档,我认为您没有正确理解它。看看你的代码,我还建议阅读一些 Python 书籍(例如 [link](http://learnpythonthehardway.org))。 (3认同)