Last active
October 8, 2020 20:16
-
-
Save moosetraveller/8a75e94eae049361cf369c3a8e3a40a2 to your computer and use it in GitHub Desktop.
Example Script: Rename File Name with Python
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
# Renames all files in a directory from OLDID_FileName.xtf to NEWID_FileName.xtf. Moves the files as well if | |
# source and target directory are not the same. A CSV file with 2 columns (OLDID,NEWID) is required. | |
import re | |
import os | |
import csv | |
# import shutil | |
source_directory = r"/Users/thozub/Desktop/files" | |
target_directory = r"/Users/thozub/Desktop/files" # directory must exist | |
matching_table_path = r"/Users/thozub/Desktop/matching.csv" | |
csv_delimiter = "," # note: a semicolon (;) is often used in German speaking regions | |
pattern = "(?P<id>\d+)(?P<name>\_.*\.xtf)" | |
regex = re.compile(pattern) | |
with open(matching_table_path, "r") as csv_file: | |
matching_table = dict(filter(None, csv.reader(csv_file, delimiter=csv_delimiter))) | |
for filename in os.listdir(source_directory): | |
if os.path.isdir(os.path.join(source_directory, filename)): | |
continue | |
match = regex.match(filename) | |
if match: | |
id = match.group("id") | |
if id in matching_table: | |
new_id = matching_table[id] | |
new_filename = regex.sub(rf"{new_id}\g<name>", filename) | |
# shutil.copyfile(os.path.join(source_directory, filename), os.path.join(target_directory, new_filename)) | |
os.rename(os.path.join(source_directory, filename), os.path.join(target_directory, new_filename)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment