Reputation: 5157
I have a folder containing 100+ mp3 files.
they respect this pattern: '000. MSK_NAME.mp3
'
I have a code to rename all my files, and it's working almost fine. Besides the fact I'm facing some trouble when the filename has some Cyrillic chars.
For example:
/musics:
'''
011. ?????? - ? ?? ???? ??? ???? (Dima Flash.mp3
012. ?????? feat. ?????? ??????? - ???????? (DJ Shtopor & DJ Oleg Petroff Remix).mp3
018. MarQ Markuz - ?????? (DJ A.G. RnDeep Remix).mp3
026. Serebro - ?????????? (DJ Denis Rublev & DJ Anton Remix).mp3
027. Samoel feat. ?????? - ????????????? ????? (Oleg Perets & Alexey Galin Remix) .mp3
029. 5sta Family - ????? (Tony Sky Sax Remix) .mp3
030. ???? ???? - ????? ????? (Dj Jurbas Nu-Disco Mix ).mp3
036. Quest Pistols - ????? ????? (DJ Denis Rublev & DJ Timur Remix).mp3
037. Serebro - ?????????? (Mickey Martini & Alexx Slam Remix).mp3
041. ??? - ???? ? ???? (Tony Sky Remix).mp3
'''
renamer.py:
# -*- coding: utf-8 -*-
import os
folder = "C:\\users\\myuser\\desktop\\musics"
for item in os.listdir(folder):
item2 = item[5:]
path = folder + "\\" + item
try:
renamed = folder + "\\" + item2
os.rename(path, renamed)
except:
#how am I supposed to create converted a filename without these Cyrillic characters ?
#i think it has something to do with using the translit() function from transliterate library
continue
print "Done."
Or maybe I should change the except part for something like this:
except:
renamed2 = translit(path, 'ru', reversed=True)
os.rename(path, renamed2)
So...
Can someone show me the right way to use translit()
to create a valid filename for the os.rename()
method ?
Maybe something like this:
print translit(u"Лорем ипсум долор сит амет", 'ru', reversed=True)
# Output: Lorеm ipsum dolor sit amеt
But while looping over the files inside the folder...
Upvotes: 1
Views: 708
Reputation: 5157
Answer:
After searching a little more I found the following solution:
Changed folder = "C:\\Users\\myuser\\Desktop\\musics"
to folder = u"C:\\Users\\myuser\\Desktop\\musics"
Added the following piece of code to my except:
part.
Fix:
except:
newName = translit(item, 'ru', reversed=True)
renamed2 = folder + "\\" + newName
os.rename(path, renamed2)
Code:
# -*- coding: utf-8 -*-
import os
from transliterate import translit
folder = u"C:\\Users\\myuser\\Desktop\\musics"
for item in os.listdir(folder):
item2 = item[:]
path = folder + "\\" + item
try:
renamed = folder + "\\" + item2
os.rename(path, renamed)
except:
newName = translit(item, 'ru', reversed=True)
renamed2 = folder + "\\" + newName
os.rename(path, renamed2)
print "done."
Upvotes: 1