正規表現
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