I am trying to make a file renamer using Python. I was able to successfully scrape Wikipedia for list of episodes, but while making the renamer file I was met with a lot of discrepancies. What I want is that instead of '.mkv' at the end I want to use exactly the extension that was matched from the if condition. Is there a way to return it?
extensions = ('.webm','.mkv','.flv','.vob','.ogv',
'.ogg','.drc','.gif','.gifv','.mng','.avi','.mov',
'.qt','.wmv','.yuv','.rm','.rmvb','.asf','.amv','.mp4',
'.m4p', '.m4v','.mpg', '.mp2', '.mpeg', '.mpe', '.mpv',
'.mpg', '.mpeg', '.m2v','.m4v','.svi','.3gp','.3g2','.mxf',
'.roq','.nsv','.f4v', '.f4p', '.f4a' ,'.f4b','.srt')
list = f.readlines()
y = 0
num = 1
for filename in os.listdir(path):
if filename.endswith(extensions):
os.rename(path+"\\"+filename,path+"\\"+str(num)+' - '+list[int(y)].strip('\n')+'.mkv') #instead of mkv, I want extension which was matched in the above if condition.
y += 1
num += 1
Well either you have to loop over the extensions one by one, or you could split the filename to get the extension.
Split by filename
for filename in os.listdir(path):
if filename.endsswith(extensions):
extension = filename.split('.')[-1] # you can use os.path.splitext too as Max Chretien suggested
# ...
Use explicit loop
for filename in os.listdir(path):
matching_extensions = filter(lambda extension: filename.endswith(extension), extensions)
if matching_extensions:
extension = matching_extensions[0]
# ...