This here Python script takes a dir tree as input, and adds every word present in the path and adds them to the filename (if the word is not already present in the filename adds it with some formatting inside existing brackets or creates brackets).
import os
import re
import shutil
import sys
def get_new_filename(full_dirs, filename):
# Split the filename and extension
name, ext = os.path.splitext(filename)
# Extract the directory names and normalize them
normalized_dirs = [normalize_dir(d) for d in full_dirs]
# Convert the filename to lowercase for case-insensitive comparison
name_lower = name.lower()
# Filter out normalized directories that already exist in the filename (case-insensitive)
normalized_dirs = [d for d in normalized_dirs if d.lower() not in name_lower]
# Find all sets of brackets in the filename
matches = re.findall(r'([.*?]|(.*?))', name)
if matches:
# Insert the new dirs inside the last set of brackets
last_brackets = matches[-1]
start, end = name.rfind(last_brackets), name.rfind(last_brackets) + len(last_brackets)
content = name[start+1:end-1]
# Add new dirs, avoiding duplicates
new_content = ', '.join([d for d in normalized_dirs if d.lower() not in content.lower().split(', ')])
if new_content:
new_name = f"{name[:start+1]}{remove_wrapped_brackets(content)}, {new_content}{name[end-1:]}"
else:
new_name = name
else:
# Create a new set of brackets at the end if there are new dirs
if normalized_dirs:
new_name = f"{name} [{' '.join(normalized_dirs)}]"
else:
new_name = name
# Return the new name and extension
return new_name + ext
def normalize_dir(directory):
# Normalize directory names: capitalize first letter, remove wrapped brackets, and handle commas
directory = remove_wrapped_brackets(directory)
return ', '.join([word.capitalize() for word in directory.split(', ')])
def remove_wrapped_brackets(text):
# Remove wrapped brackets from text
while text.startswith('(') and text.endswith(')') or text.startswith('[') and text.endswith(']'):
text = text[1:-1]
return text
def confirm_renaming(files):
print("Here is the list of files to be renamed:")
for old, new in files:
print(f"{old}n{new}n")
return input("Do you want to proceed with the renaming? (y/n): ").lower() == 'y'
def rename_files(directory):
files_to_rename = []
# Walk through the directory tree
for root, dirs, files in os.walk(directory):
# Get the relative path from the target directory and split into parts
relative_path = os.path.relpath(root, directory)
full_path_dirs = relative_path.split(os.sep)
# Include the target directory itself
if full_path_dirs[0] == '.':
full_path_dirs = full_path_dirs[1:]
full_path_dirs.insert(0, os.path.basename(directory))
for file in files:
original_full = os.path.join(root, file)
new_filename = get_new_filename(full_path_dirs, file)
new_full = os.path.join(root, new_filename)
if original_full != new_full:
files_to_rename.append((original_full, new_full))
if confirm_renaming(files_to_rename):
for old, new in files_to_rename:
shutil.move(old, new)
print("Files have been renamed successfully!")
else:
print("Renaming cancelled.")
if __name__ == "__main__":
if len(sys.argv) > 1:
directory = sys.argv[1]
rename_files(directory)
else:
print("No directory provided.")
The problem is that it should be using the entire path and put all those words in, but currently it only puts the target path’s last subdir plus further subdirs, ignoring the rest of the parent dirs.
Example with input dir d:documentsinformationmodern
d:documentinformationmodernestablished_data_[Structured].pdf
should be renamed to:
d:documentinformationmodernestablished_data_[Structured, Document, Information, Modern].pdf
but instead gets renamed to:
d:documentinformationmodernestablished_data_[Structured, Modern].pdf