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!
lost) if two names get reduced to the same shortened name after
badwordshave been removed. A set of new fnames could be kept andchecked before calling
os.renameto 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: