[Python] Rename all image files in a specific folder by shooting date and time

Introduction

How do you manage the photos taken with your mobile (smartphone) camera? In my case, after taking a picture to some extent, I copy it to my PC and erase it from my smartphone so that I try not to leave a large amount of data on my smartphone as much as possible. However, if you delete the photo from your smartphone, the serial number of the file name will be returned, and when you try to copy it to your PC, a file with the same name will be created, which is troublesome. image.png

So, in order to solve the problem of file name fog, I will introduce a method to collectively rename the image files copied to the PC using the shooting date and time.

Verification environment

Advance preparation

$ pip3 install Pillow

code

rename_images.py


from PIL import Image
from PIL.ExifTags import TAGS
from pathlib import Path
import datetime

# https://www.lifewithpython.com/2014/12/python-extract-exif-data-like-data-from-images.html
def get_exif_of_image(file):
    """Get EXIF of an image if exists.

Function to retrieve EXIF data of the specified image
    @return exif_table Exif dictionary containing data
    """
    im = Image.open(file)

    #Get Exif data
    #If it does not exist, it ends as it is. Returns an empty dictionary.
    try:
        exif = im._getexif()
    except AttributeError:
        return {}

    #Since the tag ID itself cannot be read by people, decode it
    #Store in table
    exif_table = {}
    for tag_id, value in exif.items():
        tag = TAGS.get(tag_id, tag_id)
        exif_table[tag] = value

    return exif_table

#Specify the path of the folder on the PC side that contains the image
for filename in Path("/path/to/images").glob("DSC_*.JPG"):
    exif = get_exif_of_image(filename)
    if "DateTimeOriginal" in exif:
        # strftime()Specify the format of the new name with
        new_name = Path(filename).with_name(datetime.datetime.strptime(exif["DateTimeOriginal"], "%Y:%m:%d %H:%M:%S").strftime("IMG_%Y%m%d_%H%M%S.JPG"))
        print(f"{filename} \n -> {new_name}")
        filename.rename(new_name)
    else:
        print(f"[WARNING] {filename}: no EXIF header")

Commentary

Extract the shooting date and time from the EXIF header of the image file, create a new file name in the specified format based on the shooting date and time, and rename it.

for filename in Path("/path/to/images").glob("DSC_*.JPG"):The part enumerates the image files contained in a particular folder.``DSC_*.JPG``Please match the part of to the file format generated by the smartphone camera app. This pattern is an example for Xperia.



 Use `` get_exif_of_image () `` to get the EXIF header information. This function is taken from the following page. m (_ _) m
 [Python Tips: I want to get Exif data of images --Life with Python](https://www.lifewithpython.com/2014/12/python-extract-exif-data-like-data-from-images.html)

 Since the shooting date and time is recorded under the name `` DateTimeOriginal``, the date and time character string is parsed by the `` datetime`` module. This recording format should be uniform, so there is no need to customize the `` strptime () `` argument for each camera.
 Create a new file name based on this analysis result. Change the argument of `` strftime () `` if you like. However, it's best to avoid names in the same format as the original, such as `` DSC_% Y% m% d_% H% M% S.JPG``.

 Click here for the meaning of the format strings of `` strptime () `` and `` strftime () ``.
 [8.1. datetime --- Basic Date and Time Types — Python 3.6.12 Documentation](https://docs.python.org/ja/3.6/library/datetime.html#strftime-strptime-behavior)

## Execution example

 The log will be displayed as shown below. Make sure the file is renamed correctly.

/path/to/images/DSC_0001.JPG -> /path/to/images/IMG_20190928_135805.JPG /path/to/images/DSC_0004.JPG -> /path/to/images/IMG_20191104_172704.JPG /path/to/images/DSC_0005.JPG -> /path/to/images/IMG_20191106_174423.JPG /path/to/images/DSC_0006.JPG -> /path/to/images/IMG_20191106_174752.JPG /path/to/images/DSC_0007.JPG -> /path/to/images/IMG_20191106_174808.JPG /path/to/images/DSC_0009.JPG -> /path/to/images/IMG_20191213_180056.JPG /path/to/images/DSC_0010.JPG -> /path/to/images/IMG_20191213_180103.JPG /path/to/images/DSC_0011.JPG -> /path/to/images/IMG_20191213_180112.JPG


# Supplement

 If possible, I think it's better to rename it on the smartphone side at the time of shooting.
 You can use these apps on Android. I will continue to use the app from now on.
 [Automatically rename file names when taking photos using "DSC Auto Rename" | Forget-so](http://wasure.net/dscautorename/#i)


Recommended Posts

[Python] Rename all image files in a specific folder by shooting date and time
How to stop a program in python until a specific date and time
Create a command to delete all temporary files generated in a specific folder
[Python] Get the files in a folder with Python
To represent date, time, time, and seconds in Python
Convert timezoned date and time to Unixtime in Python2.7
2 ways to read all csv files in a folder
Sort by date in python
[Python] Create a date and time list for a specified period
Get the current date and time in Python, considering the time difference
Python> Get a list of files in multiple directories> Use glob | Sort by modification time
Recursively get the Excel list in a specific folder with python and write it to Excel.
Give the history command a date and time and collect the history files of all users with a script
Determine the date and time format in Python and convert to Unixtime
Manipulate files and folders in Python
Export and output files in Python
Get a list of files in a folder with python without a path
A memo organized by renaming the file names in the folder with python
How to get the date and time difference in seconds with python
Generate all files with a specific extension
Get date and time in specified format
Read all csv files in the folder
Automate jobs by manipulating files in Python
Read and write JSON files in Python
Create a Python image in Django without a dummy image file and test the image upload
[Python] Create a list of date and time (datetime type) for a certain period
Precautions when creating a view that narrows down records by date and time
[Python] I want to collect specific files scattered in each folder in one place
Organize python modules and packages in a mess
I wrote a class in Python3 and Java
A clever way to time processing in Python
Reading and writing CSV and JSON files in Python
How to get the files in the [Python] folder
How to execute a schedule by specifying the Python time zone and execution frequency
[Python] Change the text color and background color of a specific keyword in print output
A python client application that downloads and deletes files from S3 by specifying a bucket
Checks if there is a specific character string for all files under the directory that is Python and outputs the target line
Extract "current date only" and "current date and time" with python datetime.
Convert date timezone (time difference) in Python (from string)
Include and use external Kv files in Python Kivy
Group by consecutive elements of a list in Python
Display a histogram of image brightness values in python
Recursively search for files and directories in Python and output
Summary of date processing in Python (datetime and dateutil)
It is blocked by Proxy, a connection error occurs in Python or pip, and it is retried.
An easy way to view the time taken in Python and a smarter way to improve it
A Python program that collects tweets containing specific keywords daily and saves them in csv