Skip to content

Instantly share code, notes, and snippets.

@myl7
Created April 20, 2025 11:32
Show Gist options
  • Save myl7/e8f7c887696ebcf01425f428628fc540 to your computer and use it in GitHub Desktop.
Save myl7/e8f7c887696ebcf01425f428628fc540 to your computer and use it in GitHub Desktop.
import os
import sys
def rename_items_with_chinese_numerals(directory_path):
"""
Renames files and subdirectories in the specified directory by replacing
Chinese numerals (一, 二, 三, 四, 五, 六, 七, 八, 九) with their
corresponding Arabic numerals (1, 2, 3, 4, 5, 6, 7, 8, 9).
Args:
directory_path (str): The path to the directory containing the items.
"""
# Mapping from Chinese numerals to Arabic numerals
chinese_to_arabic = {
'一': '1', '二': '2', '三': '3', '四': '4', '五': '5',
'六': '6', '七': '7', '八': '8', '九': '9',
# Add '零': '0', '十': '10' etc. if needed, but replacement logic
# might need adjustment for compound numbers (e.g., 十一, 二十).
}
# Check if the directory exists
if not os.path.isdir(directory_path):
print(f"Error: Directory not found at '{directory_path}'")
return
print(f"Scanning directory: {directory_path}")
renamed_files_count = 0
renamed_dirs_count = 0
# Iterate over each entry in the directory
# Use a list copy of listdir result to avoid issues when renaming directories in-place
try:
for item_name in list(os.listdir(directory_path)):
old_item_path = os.path.join(directory_path, item_name)
is_dir = os.path.isdir(old_item_path)
is_file = os.path.isfile(old_item_path)
# Process only files and directories
if is_file or is_dir:
# Separate the name from its extension (if it's a file)
if is_file:
name_part, extension = os.path.splitext(item_name)
else: # It's a directory
name_part = item_name
extension = "" # Directories don't have extensions in the same way
new_name_part = name_part
needs_rename = False
# Replace each Chinese numeral found in the name part
for chinese, arabic in chinese_to_arabic.items():
if chinese in new_name_part:
new_name_part = new_name_part.replace(chinese, arabic)
needs_rename = True
# If any replacements were made, proceed with renaming
if needs_rename:
new_item_name = new_name_part + extension
new_item_path = os.path.join(directory_path, new_item_name)
# Basic check to prevent overwriting if an item with the new name already exists
if os.path.exists(new_item_path):
print(f"Warning: Cannot rename '{item_name}' to '{new_item_name}' as the target already exists. Skipping.")
continue
# Attempt to rename the item
try:
os.rename(old_item_path, new_item_path)
item_type = "Directory" if is_dir else "File"
print(f"Renamed {item_type}: '{item_name}' -> '{new_item_name}'")
if is_dir:
renamed_dirs_count += 1
else:
renamed_files_count += 1
except OSError as e:
print(f"Error renaming '{item_name}' to '{new_item_name}': {e}")
except Exception as e:
print(f"An unexpected error occurred while renaming '{item_name}': {e}")
print("\nFinished processing.")
if renamed_files_count > 0:
print(f"Renamed {renamed_files_count} file(s).")
if renamed_dirs_count > 0:
print(f"Renamed {renamed_dirs_count} directorie(s).")
if renamed_files_count == 0 and renamed_dirs_count == 0:
print("No files or directories with specified Chinese numerals found or needing rename.")
except FileNotFoundError:
print(f"Error: The directory '{directory_path}' was not found.")
except PermissionError:
print(f"Error: Permission denied to access or modify items in '{directory_path}'.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# --- Script Execution ---
if __name__ == "__main__":
# Get the directory path from the user
if len(sys.argv) > 1:
target_dir = sys.argv[1] # Use command-line argument if provided
else:
target_dir = input("Please enter the full path to the directory: ")
# Clean up potential quotes from drag-and-drop or copy-paste
target_dir = target_dir.strip().strip("'\"")
rename_items_with_chinese_numerals(target_dir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment