Python批量重命名目录中以#开头的文件及子目录
# from Files & Directories The Problem
I needed to rename every file and subdirectory that starts with a # character in a target directory, stripping off that leading symbol. For example:
#222_message_split→222_message_split#013_message_split2→013_message_split2
Initial Attempt (Top-Level Files Only)
At first, I wrote a script to handle files in the immediate top-level directory. With help from pstatix, this code worked correctly:
import os PATH = "/your/target/directory" for filename in os.listdir(PATH): if filename.startswith("#"): os.rename(filename, filename[1:])
The limitation here was that it only processed files in the root folder—it didn't touch subdirectories, nor did it rename directories that had the leading #.
Extended Recursive Solution
To handle all nested files and directories, we can use os.walk() to traverse every level of the directory tree. It's important to process directories first (and update the traversal list) before handling files to avoid path conflicts:
import os PATH = "/your/target/directory" for root, dirs, files in os.walk(PATH): # Process directories first to update the tree before moving deeper for dir_name in dirs[:]: # Iterate over a copy of the dirs list to avoid iteration issues if dir_name.startswith("#"): original_path = os.path.join(root, dir_name) new_path = os.path.join(root, dir_name[1:]) os.rename(original_path, new_path) # Update the dirs list so os.walk uses the new directory name for subdirectories dirs[dirs.index(dir_name)] = dir_name[1:] # Now process all files in the current directory for filename in files: if filename.startswith("#"): original_path = os.path.join(root, filename) new_path = os.path.join(root, filename[1:]) os.rename(original_path, new_path)
Key Details to Note
- Using
dirs[:]: This creates a copy of the directories list, so renaming a directory doesn't break the ongoing iteration. We also update the originaldirslist with the new name to ensureos.walk()uses the correct path when traversing nested subdirectories. - Always use
os.path.join(): This constructs full, operating-system-agnostic paths, preventing errors from relative paths or hardcoded slashes. - Process directories first: This ensures that when we get to files inside renamed directories, the parent path is already updated and valid.
内容的提问来源于stack exchange,提问作者nEWBOB

