如何解决如何在遍历文件夹时替换文件名中的多个子字符串
假设我有一个名为fooFirst
的变量名目录。在此文件夹中,我有多个文件,包括fooSecond
,fooThird
和foo
。文件更多,但是我要做的主要事情是遍历class FooTest extends AnyFunSuite with Matchers {
//How to apply FooFirstTest,FooSecondTest,FooThirdTest here?
}
文件夹,查看每个文件名,如果它包含列表(main_dir
)中的子字符串,我想替换该子字符串与Revised Workshop FINAL.docx
。我正在尝试编写一个快速函数来执行此操作,但是它比最初看起来要难。这是到目前为止我得到的:
R1 Big Presentation. July 23,2020.pptx
然后在遍历目录时应用它:
Results. NEW - R1 Presentation. July 28,2020.pdf
这有效,但这不是理想的解决方案;有更有效的方法吗?
解决方法
您是否考虑过使用正则表达式? 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。