Paws/PythonScripts/rename_backslash.py

43 lines
1.6 KiB
Python
Raw Permalink Normal View History

2024-03-22 22:29:21 +00:00
#!/usr/bin/python3
2023-12-20 20:21:07 +00:00
import os
import sys
2023-12-20 20:36:34 +00:00
# Function to replace backslashes in filenames within a directory
2023-12-20 20:21:07 +00:00
def replace_backslash(directory):
2023-12-20 20:36:34 +00:00
# Traverse through the directory and its subdirectories
2023-12-20 20:21:07 +00:00
for root, _, files in os.walk(directory):
for filename in files:
2023-12-20 20:36:34 +00:00
# Check if the filename contains a backslash
2023-12-20 20:21:07 +00:00
if "\\" in filename:
2023-12-20 20:36:34 +00:00
# Construct the full file path
2023-12-20 20:21:07 +00:00
file_path = os.path.join(root, filename)
2023-12-20 20:36:34 +00:00
# Replace backslashes with a special character ("") in the filename
2023-12-20 20:21:07 +00:00
new_filename = filename.replace("\\", "")
2023-12-20 20:36:34 +00:00
# Construct the new file path with the modified filename
2023-12-20 20:21:07 +00:00
new_file_path = os.path.join(root, new_filename)
2023-12-20 20:36:34 +00:00
# Rename the file with the modified filename
2023-12-20 20:21:07 +00:00
os.rename(file_path, new_file_path)
2023-12-20 20:36:34 +00:00
# Print the renaming operation details
2023-12-20 20:21:07 +00:00
print(f"Renamed {file_path} to {new_file_path}")
2023-12-20 20:36:34 +00:00
# Entry point of the script
2023-12-20 20:21:07 +00:00
if __name__ == "__main__":
2023-12-20 20:36:34 +00:00
# Check if the correct number of command-line arguments is provided
2023-12-20 20:21:07 +00:00
if len(sys.argv) != 2:
2024-03-06 14:46:44 +00:00
print("Usage: python rename_backslash.py <directory_path>")
2023-12-20 20:21:07 +00:00
else:
2023-12-20 20:36:34 +00:00
directory_path = sys.argv[1] # Get the directory path from command-line argument
# Check if the specified directory exists
2023-12-20 20:21:07 +00:00
if not os.path.exists(directory_path):
print("Directory not found.")
else:
2023-12-20 20:36:34 +00:00
# Call the function to replace backslashes in filenames within the directory
2023-12-20 20:21:07 +00:00
replace_backslash(directory_path)
2023-12-20 20:36:34 +00:00