Last active
November 7, 2023 01:40
-
-
Save don1138/4754bc0c90f4b02b3480b3128b37669e to your computer and use it in GitHub Desktop.
Rename files in a directory based on a mappings 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
# Rename Files v1.1.0 | |
# Imports a mappings file in this format: | |
# current_name1,new_name1 | |
# current_name2,new_name2 | |
# ... | |
# and renames files in a MacOS directory. | |
import os | |
import shlex | |
# Ask for directory path and use shlex to sanitize the path | |
directory_path_input = input("Enter directory path: ").strip() | |
directory_path_components = shlex.split(directory_path_input) | |
directory = ' '.join(directory_path_components) | |
# Ask for mapping file and use shlex to sanitize the path | |
mapping_file_path_input = input("Enter mapping file name: ").strip() | |
mapping_file_path_components = shlex.split(mapping_file_path_input) | |
mapping_file = ' '.join(mapping_file_path_components) | |
# read mapping file into a dictionary | |
mapping = {} | |
with open(mapping_file, 'r') as f: | |
for line in f: | |
old_name, new_name = line.strip().split(',') | |
mapping[old_name.strip()] = new_name.strip() | |
# loop through files in directory and rename | |
for filename in os.listdir(directory): | |
old_path = os.path.join(directory, filename) | |
if os.path.isfile(old_path): | |
old_name, extension = os.path.splitext(filename) | |
if old_name in mapping: | |
new_name = mapping[old_name] + extension | |
new_path = os.path.join(directory, new_name) | |
os.rename(old_path, new_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment