简体   繁体   中英

How do I move and rename images from a DVR with a script?

I have a DVR camera that takes hourly images and stores each in its own folder. I would like to use a python script to move all the images into one main folder and rename them based on the folders they are located in. The current folder structure is shown below.

image 1 - MainFolder/2019-07-04/001/jpg/07/00/00[R][0@0][0].jpg

image 2 - MainFolder/2019-07-04/001/jpg/08/00/00[R][0@0][0].jpg

image 3 - MainFolder/2019-07-04/001/jpg/09/00/00[R][0@0][0].jpg

the next day the images would be

image 25 - MainFolder/2019-07-05/001/jpg/07/00/00[R][0@0][0].jpg

The /jpg/07/00 in the above reference is for 7:00am.

I would like MainFolder/2019_7_04_0700.jpg and MainFolder/2019_7_04_0800.jpg for the following hour photo.

Currently I have a folder nightmare and each image is named 00[R][0@0][0].jpg .

You could do this by using the os.walk() function to find all the camera image files, and the pathlib module to get the components of the path needed to construct the destination filename. Once you have the full paths of the source and destiniation files, you can then use the shutil.move() function to move and rename each one.

Note: The code requires at least Python 3.4 to run because of its use of pathlib and I've commented-out the line that actually does the moving and renaming, so you can safely run and test the script to see what it would do without doing any damage.

import os
import pathlib
import shutil


IMAGE_FILENAME = '00[R][0@0][0].jpg'
EXT = os.path.splitext(IMAGE_FILENAME)[1]  # Image file extension.
root = 'MainFolder'
count = 0

for dir_name, sub_dirs, files in os.walk(root, topdown=False):
    for filename in files:
        if filename == IMAGE_FILENAME:
            src = os.path.join(dir_name, filename)
            relpath = os.path.relpath(src, root)  # Relative to root folder.
            parts = pathlib.Path(relpath).parts  # Relative path components.
            dst = os.path.join(root, parts[0] + '_' + parts[3] + parts[4] + EXT)
            print(' moving "{}" to "{}"'.format(src, dst))
#            shutil.move(src, dst)
            count += 1

print('{} files moved'.format(count))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM