How to return which element from endswit matched tuple
I am trying to create a renamer file using Python. I was able to successfully clean up Wikipedia for the episode list, but I was greeted with a lot of discrepancies when creating the renamer file. I want so that instead of ".mkv" at the end, I want to use exactly the extension that was matched against the if condition. Is there a way to get it back?
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
source to share
Well, either you have to loop through the extensions one by one, or you can 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 an explicit loop
for filename in os.listdir(path):
matching_extensions = filter(lambda extension: filename.endswith(extension), extensions)
if matching_extensions:
extension = matching_extensions[0]
# ...
source to share
Otherwise, I will first extract filename
and file_extension
using os.path.splitext
.
Then, if it file_extension
matches your tuple extensions
, I'll rename it with try
except
to see if there are any errors.
for file_path in os.listdir(path):
filename, file_extension = os.path.splitext(file_path)
if file_extension in extensions:
try:
os.rename(file_path, filename + '.mkv')
except OSError:
print("Error while renaming {}".format(filename))
source to share
If I understand your question correctly, maybe the following code might work.
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.lower().split('.')[1]) in list(extensions):
os.rename(path+"\\"+filename,path+"\\"+str(num)+' - '+list[int(y)].strip('\n')+'.mkv')
y += 1
num += 1
I've only made minor changes to your code.
from: if filename.endswith(extensions):
to: if ('.'+filename.lower().split('.')[1]) in list(extensions):
Hope it helps!
source to share