【问题标题】:Rename part of the name in any files or directories in Python [duplicate]重命名Python中任何文件或目录中的部分名称[重复]
【发布时间】:2019-07-22 17:38:52
【问题描述】:

我有一个包含多个文件夹和文件的根文件夹,我需要使用 Python 重命名所有匹配的对应关系。例如,我想重命名包含单词“test”的文件和文件夹并替换为“earth”

我使用的是 Ubuntu Server 18.04。我已经尝试了一些代码。但我会留下我试过的最后一个。我认为这很容易做到,但我对 py 几乎没有任何知识,这是我目前唯一的解决方案。

import os

def replace(fpath, test, earth):
    for path, subdirs, files in os.walk(fpath):
        for name in files:
            if(test.lower() in name.lower()):
                os.rename(os.path.join(path,name), os.path.join(path,
                                            name.lower().replace(test,earth)))

预计会遍历所有文件和文件夹并将名称从test更改为earth

【问题讨论】:

    标签: python rename batch-rename


    【解决方案1】:

    这里有一些适合你的代码:

    def replace(fpath):
        filenames = os.listdir()
        os.chdir(fpath)
        for file in filenames:
            if '.' not in file:
                replace(file)
            os.rename(file, file.replace('test', 'earth'))
    

    下面是对代码的解释:

    • 首先我们得到目录中的文件名列表
    • 之后我们切换到所需的文件夹
    • 然后我们遍历文件名
    • 程序将尝试将每个文件名中的任何“test”实例替换为“earth”
    • 然后它将名称中带有'test'的文件重命名为替换'test'的版本
    • 如果它当前迭代的文件是一个文件夹,它会使用新文件夹再次运行该函数,但完成后它将恢复到原来的状态

    编辑通过子文件夹添加递归迭代。

    【讨论】:

    • 非常感谢!但是如何将代码搜索放在子文件夹中?
    • @Kulcanhez 抱歉回复晚了。我已经编辑了答案以适应这一点。
    猜你喜欢
    • 2013-12-05
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 2018-05-08
    • 2011-02-15
    • 2022-01-09
    相关资源
    最近更新 更多