我需要从文件名中删除下划线,但不是所有下划线。
原始文件:“Bob's_House_RZ.png”、“Jim_and_Judy's_House_RR.png”
期望结果:“Bob's House_RZ.png”、“Jim and Judy's_House_RR.png”
我已经编写了一些代码来替换字符,但我想知道如何为某些模式添加异常(exception),例如上面的“_RR”和“_RZ”。由于我是编程新手,我想知道最佳实践是什么。感谢您的帮助。
import os
target_dir = r"C:\Somefolder\\"
old_string = "_"
new_string = " "
extension = ".png"
count = 0
for file in os.listdir(target_dir):
if file.endswith(extension):
if file.find(old_string) > 0:
count += 1
os.rename(target_dir + "\\" + file, target_dir + "\\" + file.replace(old_string, new_string))
最佳答案
使用短正则表达式模式:
import re
extension = ".png"
# for demonstration purpose
files = ["Bob's_House_RZ.png", "Jim_and_Judy's_House_RR.png"]
pat = re.compile(r'_(?!(R[RZ]\b))')
for f in files:
if f.endswith(extension):
new_fname = pat.sub(' ', f)
print(new_fname)
# do the renaming logic
输出:
Bob's House_RZ.png
Jim and Judy's House_RR.png
关于python - 有没有办法在我的搜索和替换代码中构建异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57012828/