Paws/PythonScripts/rename_backslash.py

43 lines
1.6 KiB
Python
Raw Normal View History

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