正则表达式
正如 utdemir 所逃避的那样,正则表达式在这种情况下确实可以提供帮助。如果您从未接触过它们,一开始可能会感到困惑。查看https://www.debuggex.com/r/4RR6ZVrLC_nKYs8g以获取帮助您构建正则表达式的有用工具。
解决方案
更新的解决方案是:
import re
def rename_file(filename):
if filename.startswith('EPG') and ' ' in filename:
# \s+ means 1 or more whitespace characters
# [0-9]{2} means exactly 2 characters of 0 through 9
# \. means find a '.' character
# [0-9]{4} means exactly 4 characters of 0 through 9
newfilename = re.sub("\s+[0-9]{2}\.[0-9]{4}", '', filename)
newfilename = newfilename.replace(" ","_")
os.rename(filename, newfilename)
边注
# Remove whitespace from files where EPG named with space " " replace with "_"
for filename in os.listdir("."):
if filename.find("2013|09 ") > 0:
newfilename = filename.replace(" ","_")
os.rename(filename, newfilename)
除非我弄错了,否则您在上面所做的评论filename.find("2013|09 ") > 0
将不起作用。
鉴于以下情况:
In [76]: filename = "EPG CRO 24 Kitchen 09.2013.xsl"
In [77]: filename.find("2013|09 ")
Out[77]: -1
而您所描述的评论,您可能想要更多类似的东西:
In [80]: if filename.startswith('EPG') and ' ' in filename:
....: print('process this')
....:
process this