Created
January 30, 2025 15:49
-
-
Save maxx1128/495d7b97e91279cf1d0176b6f6d37324 to your computer and use it in GitHub Desktop.
Rename Download Book File Name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
import os | |
def parse_filename(filename): | |
# Remove the URL at the start | |
cleaned_filename = re.sub(r'^_.*?_', '', filename) | |
# Split the remaining string into title and author | |
parts = cleaned_filename.rsplit('_-_', 1) | |
if len(parts) == 2: | |
title = parts[0].replace('_', ' ') | |
author = parts[1].replace('_', ' ') | |
return title, author | |
else: | |
return None, None | |
def rename_files_in_directory(directory_path): | |
for filename in os.listdir(directory_path): | |
if os.path.isfile(os.path.join(directory_path, filename)): | |
title, author = parse_filename(filename) | |
if title and author: | |
new_filename = f"{title}, {author}" | |
os.rename( | |
os.path.join(directory_path, filename), | |
os.path.join(directory_path, new_filename) | |
) | |
# Example usage | |
directory_path = '/Users/maxwell/Downloads' | |
rename_files_in_directory(directory_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment