【问题标题】:How to replace multiple substrings in a filename while iterating through a folder遍历文件夹时如何替换文件名中的多个子字符串
【发布时间】:2020-12-10 03:37:26
【问题描述】:

假设我有一个变量名为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.x loops replace substring


【解决方案1】:

您是否考虑过使用正则表达式? 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

【讨论】:

  • 效果很好。感谢您对使用re 模块的建议。
猜你喜欢
  • 2017-02-25
  • 2016-09-09
  • 1970-01-01
  • 1970-01-01
  • 2014-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-25
相关资源
最近更新 更多