使用python批量搜索并替换文件名中的字符串
我正在尝试编写一个小的 python 脚本,通过搜索和替换来重命名一堆文件名。例如:
原始文件名: MyMusic.Songname.Artist-mp3.iTunes.mp3
意图结果: Songname.Artist.mp3
到目前为止我得到的是:(
#!/usr/bin/env python
from os import rename, listdir
mustgo = "MyMusic."
filenames = listdir('.')
for fname in fnames:
if fname.startswith(mustgo):
rename(fname, fname.replace(mustgo, '', 1))
据我所知是从这个网站得到的)
无论如何,这只会删除开头的字符串,但不会删除文件名中的字符串。
另外,我想使用一个单独的文件(例如 badwords.txt),其中包含应搜索和替换的所有字符串,以便我可以更新它们而无需编辑整个代码。
Content of badwords.txt
MyMusic.
-mp3
-MP3
.iTunes
.itunes
我已经寻找了很长一段时间但还没有找到任何东西。将不胜感激任何帮助!
谢谢你!
I am trying to write a small python script to rename a bunch of filenames by searching and replacing. For example:
Original filename:
MyMusic.Songname.Artist-mp3.iTunes.mp3
Intendet Result:
Songname.Artist.mp3
what i've got so far is:
#!/usr/bin/env python
from os import rename, listdir
mustgo = "MyMusic."
filenames = listdir('.')
for fname in fnames:
if fname.startswith(mustgo):
rename(fname, fname.replace(mustgo, '', 1))
(got it from this site as far as i can remember)
Anyway, this will only get rid of the String at the beginning, but not of those in the filename.
Also I would like to maybe use a seperate file (eg badwords.txt) containing all the strings that should be searched for and replaced, so that i can update them without having to edit the whole code.
Content of badwords.txt
MyMusic.
-mp3
-MP3
.iTunes
.itunes
I have been searching for quite some time now but havent found anything. Would appreciate any help!
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
丢失)如果两个名称在之后减少为相同的缩写名称
坏词
已被删除。可以保留一组新的 fname在调用 os.rename 之前进行检查以防止丢失数据
名称冲突。
等价的正则表达式。上面是用来转换坏词的
(例如
'.iTunes'
)转换为正则表达式(例如r'\.iTunes'
)。您的坏词列表似乎表明您想忽略大小写。你
可以通过将
'(?i)'
添加到pat
的开头来忽略大小写:lost) if two names get reduced to the same shortened name after
badwords
have been removed. A set of new fnames could be kept andchecked before calling
os.rename
to prevent losing data throughname collisions.
equivalent regular expression. It is used above to convert badwords
(e.g.
'.iTunes'
) into regular expressions (e.g.r'\.iTunes'
).Your badwords list seems to indicate you want to ignore case. You
could ignore case by adding
'(?i)'
to the beginning ofpat
: