1
我把使用mac程序Patterns的正则表达式放在一起,当我在我的python脚本中使用代码时,我无法获取对文件名所做的更改。我知道你需要将re.sub
的输出分配给一个新的字符串,这是一个常见的错误。我这样做了,但仍然无法获得正确的结果。如何使用re.sub实际替换文件名?
这里是我的代码与给定文件名称输入:
real.time.With.bill.maher.JUST.OVERTIME.2014.01.31.WEB-DL.Shadoe
real time with bill maher 2014 01 24 hdtv x264-2hd.mp4
Real Time With Bill Maher 2014.02.07.hdtv.x264-2hd.mp4
import re
import os
path = "/Users/USERNAME/Movies"
pattern = "(real[. ]time[. ]with[. ]bill[. ]maher[. ])"
replacement = "Real Time with Bill Maher "
def renamer(path, pattern, replacement):
for dirpath,_,file in os.walk(path):
for oldname in file:
if re.search(pattern, oldname, re.I):
newname = re.sub(pattern, replacement, oldname)
newpath = os.path.join(dirpath, newname)
oldpath = dirpath + "/" + oldname
print newpath + " < new"
print oldpath
os.rename(oldpath, newpath)
renamer(path, pattern, replacement)
谢谢,就是这样!仅供参考:代码工作时没有明确定义标志('flags =') –
@ macmadness86,'flags'是可选的。顺便说一句,你什么意思'作品'?不会引发异常? – falsetru
正是。并正确写入新的文件名。我无法在30秒内正确回答你的答案。 –