Skip to content

Instantly share code, notes, and snippets.

Last active July 2, 2019 22:47
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Python 3 script to rename series files in absolute number episode format using TVDB API.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
In order to use this module, mediainfo library needs to be
installed on your system. Visit
for more information, download and installation details.
from tvdb_api import Tvdb, tvdb_shownotfound
from requests.exceptions import ConnectionError
from glob import glob
from re import sub
from os import rename
from os.path import splitext
from pymediainfo import MediaInfo
from sys import exit
files = [file for file in glob('*.*') for track in
MediaInfo.parse(file).tracks if track.track_type == 'Video']
if not files:
print("Permission to read files denied or no video "
"files in the directory!")
n = 0
name = []
for file_name in files:
tvdb = Tvdb(language="en")
name = sub(r"\[.*?\]|\(.*?\)|_|\W|\d|\bEp\b", " ",
splitext(file_name)[0]).strip(" ")
show = tvdb[name]
seasons = [key for key in show for value in show[key]]
episodes = [value for key in show for value in show[key]]
absoluteNumbers = [episode['absoluteNumber'] for season
in show.values() for episode in season.values()]
i = 0
if not sub(r"\[.*?\]|\(.*?\)|\D", '', splitext(file_name)[0]):
print(f'{file_name} can not be renamed!')
for i in range(len(absoluteNumbers)):
if (int(sub(r"\[.*?\]|\(.*?\)|\D", '',
splitext(file_name)[0])) ==
new_name = (sub(r"[!?:@|</*\"\\>]", '',
show['seriesName']) + " "
+ str(f'S{seasons[i]:02}', )
+ str(f'E{episodes[i]:02}', )
+ splitext(file_name)[1])
rename(file_name, new_name)
n += 1
print(f"{file_name} -> {new_name}")
except PermissionError:
print(f"Cannot write {file_name}, permission "
except ValueError:
except tvdb_shownotfound:
print(f"Show {name} not found!")
except ConnectionError:
print("No Internet connection!")
except KeyboardInterrupt:
if n == 0:
print("No files renamed!")
elif n == 1:
print(f"\n{n} file successfully renamed!")
print(f"\n{n} files successfully renamed!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment