Adding dir names in a tree to the filenames only works for target subdir names, not full path

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật