[英]How can I use re.sub to actually replace the filenames?
I put together a regular expression that works using the mac program Patterns , when I use the code in my python script, I cannot get the changes made to the filenames. 我将使用Mac程序Patterns的正则表达式放在一起,当我在python脚本中使用代码时,无法获得对文件名所做的更改。 I know that you need to assign the output of re.sub
to a new string, which is a common error. 我知道您需要将re.sub
的输出分配给新字符串,这是一个常见错误。 I did that, but I still cannot get the correct results. 我做到了,但仍然无法获得正确的结果。
Here is my code with the given file names as input: 这是给定文件名作为输入的我的代码:
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)
The code is missing re.I
flag in re.sub
call: 该代码缺少re.sub
调用中的re.I
标志:
>>> pattern = "(real[. ]time[. ]with[. ]bill[. ]maher[. ])"
>>> replacement = "Real Time with Bill Maher "
>>> re.sub(pattern, replacement, 'real.time.With.bill.maher.JUST.OVERTIME.2014.01.31.WEB-DL.Shadoe')
'real.time.With.bill.maher.JUST.OVERTIME.2014.01.31.WEB-DL.Shadoe'
>>> re.sub(pattern, replacement, 'real.time.With.bill.maher.JUST.OVERTIME.2014.01.31.WEB-DL.Shadoe', flags=re.I)
'Real Time with Bill Maher JUST.OVERTIME.2014.01.31.WEB-DL.Shadoe'
You should specify flags
as keyword argument, otherwise it is recognized as count
(replace count) argument. 您应将flags
指定为关键字参数,否则将被识别为count
(替换计数)参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.