python-3.x - 如何在遍历文件夹时替换文件名中的多个子字符串
问题描述
假设我有一个名为main_dir
. 在这个文件夹中,我有多个文件,包括Revised Workshop FINAL.docx
、R1 Big Presentation. July 23, 2020.pptx
和Results. 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 有一个名为“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
推荐阅读
- javascript - 读取循环内对象的变量值
- typescript - 做什么
> 在 TypeScript 中的函数名之后是什么意思? - python - 为什么我们在 super.save() 中使用 * args 和 **kwargs
- r - R lattice plot - 添加外边距,将文本添加到边距并向下移动主要标题
- c - 如何使用 CMake 从命令行修改或重新定义宏值?
- rust - 如何为这个 rustlings 问题 (errors5) 返回正确的错误?
- php - 从 PHP 中的多维数组中删除 kay
- javascript - 为什么我在 Solidity 智能合约测试中收到 AssertionError 错误?
- java - 如何解决 Jetty AbstractHandler 不将请求发送到下一个
- oracle - 在 Toad 数据点中查找运行时