首页 > 解决方案 > 如何在遍历文件夹时替换文件名中的多个子字符串

问题描述

假设我有一个名为main_dir. 在这个文件夹中,我有多个文件,包括Revised Workshop FINAL.docxR1 Big Presentation. July 23, 2020.pptxResults. NEW - R1 Presentation. July 28, 2020.pdf. 还有更多文件,但我要做的主要事情是遍历我的main_dir文件夹,查看每个文件名,如果它包含来自列表 ( bad_list = [" ", ".", "-", "&", ",", "___", "__"]) 的子字符串,我想用"_". 我正在尝试编写一个快速函数来执行此操作,但它比最初看起来更难。这是我到目前为止所得到的:

def filename_replacer(file_name):
    bad_list = [".", "-", "&", ",", "___", "__"]
    new_name = file_name.replace(" ", "_")
    for item in bad_list:
        new_name = new_name.replace(item, "_")
        
    return new_name

然后我会在遍历目录时应用它:

for subdir, dirs, files in os.walk(new_dir_path):
    for filename in files:
        print(filename)
        new_name = filename_replacer(filename)
        os.rename(filename,new_name)            

这可行,但不是理想的解决方案;有没有更有效的方法来做到这一点?

标签: python-3.xloopsreplacesubstring

解决方案


您是否考虑过使用正则表达式?Python 有一个名为“re”的正则表达式包。

import re

def filename_replacer(file_name):
    # Replace .-&, with _ (will convert "test&-.,123" to "test____123" )
    new_name = re.sub( "[\.\-&,_]", "_", file_name )
    
    # Replace 2+ '_' with 1 '_' (will convert "test____123" to "test_123" )
    new_name = re.sub( "[_]{2,}", "_", new_name )
    # Comment this out if you don't want multiple underscores to be replaced by a single underscore
        
    return new_name

推荐阅读