Move many files to date-based directories

Here is the story: as the result of my security camera timelapse project, I ended up with a ton of files stored in a single directory. I want them to be divided into day-based directories. The photos taken each day should be placed in a separate directory.

For me, the simplest way to achieve this was to write a simple Python script:

import os
from datetime import timedelta, date

start_date = date(2020, 11, 26)
end_date = date(2020, 12, 10)
path = os.getcwd()
subdir_name = '/capture/'

def daterange(start_date, end_date):
    for n in range(int((end_date - start_date).days)):
        yield start_date + timedelta(n)

print ("The current working directory is %s" % path)

for single_date in daterange(start_date, end_date):
    this_path = path + subdir_name + single_date.strftime("%Y%m%d")
    except OSError:
        print("Creation of the directory %s failed" % this_path)
        print("%s created" % this_path)

for fname in os.listdir(path + subdir_name):
    if ((fname[0:4] == "img-") & (os.path.isfile(os.path.join(path + subdir_name, fname)))):
        print("Moving %s" % fname)
        os.rename(os.path.join(path + subdir_name, fname),
                os.path.join(path + subdir_name + fname[4:12], fname))

The beginning of the script contains the setup variables. The start date of my capture, the end date (plus one day), and the name of the subdirectory in which the files are stored (relatively to my Python script).

In the first step, the script is creating a directory for each date. I decided to create them without dividers in the name, so they look like “20201127” instead of “2020-11-27”. You can change this by adjusting strftime parameters.

Once the directories are created, I take all the files in the directory and loop through them. My capture script is creating files using such a pattern:

…. and so on

This is why I’m looking only for files that begin with ‘img-‘ and I simply move them to the directories based on the date stored in the file name. If there is no such information in your file name, you have to check the creation (or modification) date first and decide where to put them based on this info.

Leave a Reply

Your email address will not be published. Required fields are marked *