Skip to content

Instantly share code, notes, and snippets.

@ReinforceZwei
Created June 9, 2022 08:57
Show Gist options
  • Save ReinforceZwei/ce78a0574accc18c4a4f28b0ba0501d0 to your computer and use it in GitHub Desktop.
Save ReinforceZwei/ce78a0574accc18c4a4f28b0ba0501d0 to your computer and use it in GitHub Desktop.
Rename subtitle file (e.g. .ass file) to match video file name so that video player can pick them up automically
import os, sys
from os import listdir
from os.path import isfile, join
from pathlib import Path
def must_get_dir_params(argv):
video_dir = ""
ass_dir = ""
if len(argv) == 3:
video_dir = argv[1]
ass_dir = argv[2]
if video_dir == "" or ass_dir == "":
print("Require parmeters: [video directory] [ass directory]")
sys.exit(1)
return (video_dir, ass_dir)
else:
print("Require parmeters: [video directory] [ass directory]")
sys.exit(1)
def list_dir_file(dir):
exclude_files = ['Thumbs.db', '*.txt']
l = sorted([f for f in listdir(dir) if isfile(join(dir, f))])
n = []
for f in l:
ok = True
for ex in exclude_files:
if wildcard_match(ex, f):
ok = False
if ok:
n.append(f)
return n
def wildcard_match(pattern:str, target):
if pattern.startswith('*'):
if target.endswith(pattern.replace('*', '')):
return True
else: return False
elif pattern.endswith('*'):
if target.startswith(pattern.replace('*', '')):
return True
else: return False
else:
if pattern == target:
return True
else: return False
def get_renamed_ass(video_name, ass_name):
if len(video_name) == len(ass_name):
ass_ext = Path(ass_name[0]).suffix
for ass in ass_name:
if Path(ass).suffix != ass_ext:
raise ValueError("ASS file extension not same")
renamed_list = []
for video in video_name:
renamed_list.append(Path(video).stem + ass_ext)
return renamed_list
else:
raise ValueError("Number of video and ass file not match")
def rename_ass(ass_dir, old_name, new_name):
for idx, name in enumerate(new_name):
to_be_rename = os.path.join(ass_dir, old_name[idx])
new_ass_path = os.path.join(ass_dir, name)
os.rename(to_be_rename, new_ass_path)
if __name__ == "__main__":
video_dir, ass_dir = must_get_dir_params(sys.argv)
video_list = list_dir_file(video_dir)
ass_list = list_dir_file(ass_dir)
new_ass_list = get_renamed_ass(video_list, ass_list)
rename_ass(ass_dir, ass_list, new_ass_list)
print("Done")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment