#100DaysofCode – a file renaming script (python)

I can’t stand doing the same task more than 10 times in a row if there’s a way to automate it. My recent website projects have involved a lot of compressing and renaming image files, and the process is tedious. I fixed it:


# !/usr/bin/python

''' takes source and destination strings as input, and changes names of files in the local directory. '''

import os, sys

def fileRename(src, dest):
    for filename in os.listdir("."):
        if src in filename:
            newname = filename.replace(src, dest)
            os.rename(filename, newname)

def main():
    src = input("What is the substring you need to change? ")
    dest = input("What would you like to replace it with? ")
    fileRename(src, dest)


# ls
print("Process complete! New directory contents:\n{}".format(os.listdir(os.getcwd())))

(part of my tiny scripts repository on github.)

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.