Skip to content

Instantly share code, notes, and snippets.

@jpcofr
Created June 2, 2023 11:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpcofr/1d02a03b648741c1b053a40a37f2dcec to your computer and use it in GitHub Desktop.
Save jpcofr/1d02a03b648741c1b053a40a37f2dcec to your computer and use it in GitHub Desktop.
Replace Spaces with Underscores in File Names
#!/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