-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsanitizeFilenames.py
32 lines (25 loc) · 1.32 KB
/
sanitizeFilenames.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import os
import re
def sanitize_filename(filename):
# Mimic Django's slugify behaviour
filename = re.sub(r'[\':?]', '_', filename)
filename = re.sub(r'&', 'and', filename)
filename = re.sub(r'[^\w\s-]', '', filename) # Remove non-alphanumeric characters except for spaces and hyphens
filename = re.sub(r'[-\s]+', '-', filename) # Replace spaces and hyphens with a single hyphen
return filename.strip('-').lower() # Convert to lowercase and trim leading/trailing hyphens
def sanitize_mp3_files(directory):
print(directory)
for file in os.listdir(directory):
if file.lower().endswith('.mp3'):
original_path = os.path.join(directory, file)
sanitized_name = sanitize_filename(os.path.splitext(file)[0]) + '.mp3'
sanitized_path = os.path.join(directory, sanitized_name)
if original_path != sanitized_path:
# os.rename(original_path, sanitized_path)
print(f"Renamed: '{file}' -> '{sanitized_name}'")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Sanitize filenames of all MP3 files in a directory.")
parser.add_argument("directory", help="Directory containing the MP3 files to sanitize")
args = parser.parse_args()
sanitize_mp3_files(args.directory)