Created
July 25, 2024 19:40
-
-
Save cassidoo/ac63f0723c80a0d0926347e72091089f to your computer and use it in GitHub Desktop.
A script to replace all of the spaces with dashes in the file and folder names of a directory
This file contains hidden or 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
# Place this file in the folder that you want to edit, and then run `python spaces-to-dashes.py` | |
import os | |
def rename_files_and_folders(root_directory): | |
for dirpath, dirnames, filenames in os.walk(root_directory, topdown=False): | |
# Rename files | |
for filename in filenames: | |
if ' ' in filename: | |
old_file_path = os.path.join(dirpath, filename) | |
new_file_name = filename.replace(' ', '-') | |
new_file_path = os.path.join(dirpath, new_file_name) | |
os.rename(old_file_path, new_file_path) | |
print(f'Renamed file: {old_file_path} -> {new_file_path}') | |
# Rename folders | |
for dirname in dirnames: | |
if ' ' in dirname: | |
old_dir_path = os.path.join(dirpath, dirname) | |
new_dir_name = dirname.replace(' ', '-') | |
new_dir_path = os.path.join(dirpath, new_dir_name) | |
os.rename(old_dir_path, new_dir_path) | |
print(f'Renamed folder: {old_dir_path} -> {new_dir_path}') | |
if __name__ == "__main__": | |
root_directory = os.getcwd() | |
rename_files_and_folders(root_directory) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment