Created
June 2, 2023 11:58
-
-
Save jpcofr/1d02a03b648741c1b053a40a37f2dcec to your computer and use it in GitHub Desktop.
Replace Spaces with Underscores in File Names
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os | |
import sys | |
# Check if the file name is provided as an argument | |
if len(sys.argv) < 2: | |
print("Error: No file name provided.") | |
sys.exit(1) | |
# Extract the file name from the provided path | |
file_path = sys.argv[1] | |
file_name = os.path.basename(file_path) | |
# Check if the file exists | |
if not os.path.exists(file_path): | |
print("Error: File does not exist.") | |
sys.exit(1) | |
# Replace spaces with underscores in the file name | |
new_file_name = file_name.replace(' ', '_') | |
# Rename the file | |
new_file_path = os.path.join(os.path.dirname(file_path), new_file_name) | |
os.rename(file_path, new_file_path) | |
print("File renamed successfully.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment