Untitled
unknown
plain_text
a year ago
1.9 kB
7
Indexable
import os
import sys
def rename_trailing_space_entries(root_dir):
for dirpath, dirnames, filenames in os.walk(root_dir, topdown=False):
# Rename files ending with a space
for filename in filenames:
if filename.endswith(' '):
old_file_path = os.path.join(dirpath, filename)
new_filename = filename.rstrip()
new_file_path = os.path.join(dirpath, new_filename)
try:
os.rename(old_file_path, new_file_path)
print(f"Renamed file:\nFrom: '{old_file_path}'\nTo: '{new_file_path}'\n")
except Exception as e:
print(f"Error renaming file '{old_file_path}': {e}")
# Rename directories ending with a space
for dirname in dirnames:
if dirname.endswith(' '):
old_dir_path = os.path.join(dirpath, dirname)
new_dirname = dirname.rstrip()
new_dir_path = os.path.join(dirpath, new_dirname)
try:
os.rename(old_dir_path, new_dir_path)
print(f"Renamed directory:\nFrom: '{old_dir_path}'\nTo: '{new_dir_path}'\n")
# Update dirnames to reflect the renamed directory
dirnames[dirnames.index(dirname)] = new_dirname
except Exception as e:
print(f"Error renaming directory '{old_dir_path}': {e}")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python rename_trailing_space.py <root_directory>")
sys.exit(1)
root_directory = sys.argv[1]
if not os.path.exists(root_directory):
print(f"The directory '{root_directory}' does not exist.")
sys.exit(1)
rename_trailing_space_entries(root_directory)
Editor is loading...
Leave a Comment