Skip to content

Instantly share code, notes, and snippets.

@Furkanzmc
Last active April 20, 2017 11:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Furkanzmc/5f070b72d0429fd74d08a84ffda6bca4 to your computer and use it in GitHub Desktop.
Save Furkanzmc/5f070b72d0429fd74d08a84ffda6bca4 to your computer and use it in GitHub Desktop.
Python Script to Replace the File Names in a Folder
#
# Python Script to Replace the File Names in a Folder
# Changes by @m-etka
#
import os
# Get working directory
path = os.getcwd()
# Read desired input as string
before = raw_input("Replace From: ")
after = raw_input("Replace To: ")
# Loop files in the directory
for filename in os.listdir(path):
filename_without_ext = os.path.splitext(filename)[0]
extension = os.path.splitext(filename)[1]
# Find before text in filename, if exists change the value
if before in filename_without_ext:
new_file_name = filename_without_ext.replace(before, after)
new_file_name_with_ext = new_file_name + extension
os.rename(
os.path.join(path, filename),
os.path.join(path, new_file_name_with_ext)
)
@m-etka
Copy link

m-etka commented Apr 20, 2017

I changed input() with raw_input() in order to get rid of casting errors.
Also changed path to working directory (Original one have problems with macOS).
Lastly, added a control for before text in filename.

# 
# Python Script to Replace the File Names in a Folder 
# 

import os

# Get working directory
path = os.getcwd()

# Read desired input as string
before = raw_input("Replace From: ")
after = raw_input("Replace To: ")

# Loop files in the directory
for filename in os.listdir(path):
    filename_without_ext = os.path.splitext(filename)[0]
    extension = os.path.splitext(filename)[1]

    # Find before text in filename, if exists change the value
    if before in filename_without_ext:
        new_file_name = filename_without_ext.replace(before, after)
        new_file_name_with_ext = new_file_name + extension
        os.rename(
            os.path.join(path, filename),
            os.path.join(path, new_file_name_with_ext)
        )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment