I have build a script which renames all the file names in the CWD except the ones the script skips to make all the file names all have a slick and the same format. I build it cause sometimes when you download files or something it's all formatted differently. Some people use".,-_" or upper case everything or w.e. and that's ugly to see plus it's hard to work with so i wrote this script to make everything have one format.
import os,sys,re,time
start=time.time()
skip2=['.py']
skip3=['.Jpg','.jpg']
count=0
lijst=os.listdir()
r = re.compile(r'[-_ ]+')
def solve(s):
name, ext = os.path.splitext(s)
artist, song = name.rsplit('-', 1)
artist = r.sub(' ', artist).title().strip()
song = r.sub(' ', song).title().strip()
ext = ext.lower()
return artist + ' - ' + song + ext
for x in lijst:
if x[-3:] not in skip2 and x[-4:] not in skip3:
y=x
if __name__ == '__main__':
x=solve(x)
x=re.sub('Ft' ,'Ft.' ,x)
x=re.sub('Feat' ,'Feat.' ,x)
x=re.sub('Extended Mix' ,'(Extended Mix)' ,x)
x=re.sub('Original Mix' ,'(Original Mix)' ,x)
x=x.replace('(((' ,'(')
x=x.replace('((' ,'(')
x=x.replace(')))' ,')')
x=x.replace('))' ,')')
x=re.sub("\.\.",".", x)
x=re.sub(' 'or' ' ,' ' ,x)
print(x)
os.rename (y,x)
count=count+1
print("%s Files edited."%count)
print('It took', time.time()-start, 'seconds.')
input("Press enter to exit...")
Many thanks to Ashwini Chaudhary I solved my problems and will leave the script on here so other people can use it as well.
You can use os.path.splitext
to separate filename and extension first and then do some processing on filename and finally join them back:
import os
import re
r = re.compile(r'[-_ ]+')
def solve(s):
name, ext = os.path.splitext(s)
artist, song = name.rsplit('-', 1)
artist = r.sub(' ', artist).title().strip()
song = r.sub(' ', song).title().strip()
return artist + ' - ' + song + ext
if __name__ == '__main__':
print solve("Alibi- Eternity_ Ft_ Armin Van Buuren and Dj Tiesto_.mp3")
print solve( "05-orjan_nilsen-so_long_radio__original_mix.mp3")
print solve( "05 - Orjan Nilsen - So Long Radio (Original Mix).mp3")
Output:
Alibi - Eternity Ft Armin Van Buuren And Dj Tiesto.mp3
05 Orjan Nilsen - So Long Radio Original Mix.mp3
05 Orjan Nilsen - So Long Radio (Original Mix).mp3