Python 3.x 如何在遍历文件夹时替换文件名中的多个子字符串
假设我有一个名为Python 3.x 如何在遍历文件夹时替换文件名中的多个子字符串,python-3.x,loops,replace,substring,Python 3.x,Loops,Replace,Substring,假设我有一个名为main\u dir的变量名目录。在这个文件夹中,我有多个文件,包括修订的Workshop FINAL.docx,R1大型演示文稿。2020年7月23日。pptx,以及结果。新-R1演示文稿。2020年7月28日.pdf。还有更多的文件,但我想做的主要事情是遍历我的main\u dir文件夹,查看每个文件名,如果它包含列表中的子字符串(bad\u list=[“”,“,”,“-”,“&“,”,“,”,“\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
main\u dir
的变量名目录。在这个文件夹中,我有多个文件,包括修订的Workshop FINAL.docx
,R1大型演示文稿。2020年7月23日。pptx
,以及结果。新-R1演示文稿。2020年7月28日.pdf。还有更多的文件,但我想做的主要事情是遍历我的main\u dir
文件夹,查看每个文件名,如果它包含列表中的子字符串(bad\u list=[“”,“,”,“-”,“&“,”,“,”,“\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。我试图写一个快速的函数来实现这一点,但它比最初看起来更难。到目前为止,我得到的是:
def filename\u replacer(文件名):
坏列表=[“”、“-”、“&”、“、”、“、”、“uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
新建名称=文件名称。替换(“,”)
对于错误列表中的项目:
新名称=新名称。替换(项目“”)
返回新名称
然后,我将在遍历目录时应用它,如下所示:
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
这回答了你的问题吗?这很有效。感谢您提出使用re
模块的建议。