Last active
August 6, 2024 01:55
-
-
Save Akczht/d8fdf77a539c894d4d70dd7531299c08 to your computer and use it in GitHub Desktop.
Renames files in a directory using names from a text file.
This file contains 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 os | |
import pathlib | |
def rename_files(directory, names_file, add_numbers=False, keep_extension=True): | |
"""Renames files in a directory using names from a text file, sorting files by name, optionally adding numbers with leading zeros, and optionally keeping extensions. | |
Args: | |
directory: The path to the directory containing the files. | |
names_file: The path to the text file with new names. | |
add_numbers: If True, adds numbers to the new file names. | |
keep_extension: If True, keeps the original file extensions. | |
""" | |
with open(names_file, 'r') as f: | |
new_names = f.read().splitlines() | |
files = sorted([f for f in os.listdir(directory) if not f.startswith('.')]) | |
if not files: | |
print("No non-hidden files found in the directory.") | |
return | |
if len(files) != len(new_names): | |
print("Number of non-hidden files and names don't match.") | |
return | |
num_files = len(files) | |
num_digits = len(str(num_files)) | |
for i, file in enumerate(files): | |
old_path = os.path.join(directory, file) | |
base_name = new_names[i] | |
old_ext = pathlib.Path(file).suffix | |
if add_numbers: | |
new_name = f"{str(i+1).zfill(num_digits)} - {base_name}" | |
else: | |
new_name = base_name | |
if keep_extension: | |
new_name += old_ext | |
new_path = os.path.join(directory, new_name) | |
try: | |
os.rename(old_path, new_path) | |
print(f"Renamed {old_path} to {new_path}") | |
except OSError as e: | |
print(f"Error renaming file: {e}") | |
# Example usage | |
directory = "path/to/your/directory" | |
names_file = "path/to/your/names.txt" | |
add_numbers = input("Add numbers to file names? (y/n): ").lower() == "y" | |
keep_extension = input("Keep original file extensions? (y/n): ").lower() == "y" | |
rename_files(directory, names_file, add_numbers, keep_extension) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment