Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Small tool to rename audio files in a directory
#!/usr/local/bin/python3
# -*- coding: utf-8 -*-
import os
import stat
import re
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"-t", "--test",
help = "test run, only prints converted filenames",
action = "store_true")
parser.add_argument(
"-e", "--end",
help = "remove string after - from end of filenames",
action = "store_true")
parser.add_argument(
"-r", "--remove",
help = "remove REMOVE (quoted) string from filenames")
parser.add_argument(
"-b", "--begin",
help = "remove BEGIN chars from beginning of filenames")
parser.add_argument(
"-a", "--add",
help = "add ADD chars before beginning of filenames")
args = parser.parse_args()
replacer = (("&", "and"), ("!", ""), ("?", ""), ("ü", "ue"), ("ä", "ae"),
(" ", "_"), (",", ""))
filelist = os.listdir()
filelist.sort()
for name in filelist:
if name.lower().endswith((".mp3", ".flac", ".ogg", ".m4a")):
if(args.begin):
new_name = name[int(args.begin):]
else:
new_name = name
if(args.remove):
new_name = new_name.replace(args.remove, "")
new_name = new_name.casefold()
for i, j in replacer:
new_name = new_name.replace(i, j)
if(args.end):
new_name = re.sub(r"^(.+)(-.+)(\..+)", r"\1\3", new_name)
new_name = re.sub(r"^([0-9]+)_+([\(a-z0-9])", r"\1_-_\2", new_name)
new_name = re.sub(r"^([0-9]+)_*-_*([\(a-z0-9])", r"\1_-_\2", new_name)
new_name = re.sub(r"^([0-9]+)_*\.+_*([\(a-z0-9])", r"\1_-_\2", new_name)
new_name = re.sub(r"^(cd[0-9]+)_*-_*([0-9]+)_*-*_*([\(a-z0-9])",
r"\1_-_\2_-_\3", new_name)
if(args.add):
new_name = args.add + new_name
if args.test:
print(name + " -> " + new_name)
else:
try:
os.rename(name, new_name)
os.chmod(new_name, stat.S_IROTH | stat.S_IRGRP |
stat.S_IRUSR | stat.S_IWUSR)
except OSError:
print("File I/O error")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.