Day 27: Renaming Image Files And Photos Bulkwise With Python

 

One of my most dreaded tasks on the computer is the renaming of images. When I import them from the digicam they’re usually just numbered.

 

I like to name my photos with a concrete name. For example „rome_2015“ or „linus“ when I have taken images of my dog. The images also get a numbered index 01,02,03,aso.

 

Well it’s dreaded not anymore because I wrote a little Python script that will do all the tedious work for me in an instance.

 

Not only do we rename the images, the program will also detect other files (like system files) and leave them untouched.

 

Here is a before and after:

 

 

To do this the python script needs to know the directory where the photos are located, the desired filename and what file type we like to change (.jpg)

 

Here is the code (the comments explain the function line by line)

 

import os

directory = "img/"                              # get the image-directory
absolute_dir = os.getcwd()                      # get your current working dir
complete_dir = absolute_dir + "/" + directory   # built a complete path to the images

#if you would need the desktop dir on mac - use the line below
#complete_dir = os.path.expanduser("~/Desktop/test/")

num_of_files = 0                                # set counter for image-numbers
name = "linus"                                # what you want to name you images

# go through every file in given dir
for filename in os.listdir(complete_dir):
    if filename.endswith(".jpg"):               # only operate on .jpg files, can be changed to any filetype
        num_of_files += 1                       # thats the number we indes our fotos with

        new_name = name + "_" + str(num_of_files) + ".jpg" # build the new file name

        # rename the file, we need complete_dir here because
        # listdir and rename work on different (absolute and increment) directorys
        # otherwise we will get an error
        os.rename(complete_dir + filename, complete_dir + new_name)

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.