1

How can I edit a folder of files and rename all the files in that folder by finding a fixed string of characters and then take that string plus four characters and move it to the prefix of the file name?

As an example, I have folder of pictures with various names but within each name is the date. I would like to take that date string and move it to the beginning of the files name.

Here is a file name:

AK_ADVOUTPOSTB1CHARACTER_20171202_406828017946.jpg

as you can see there is a string of "20171202" in this file but each file may have a different month and day but they are all "2017".

So I'd like to find the string starting with "2017", then take that plus the next four characters and move it to the beginning of the file.

As an ultimate solution, I'd like to be able to find the string "_2017" take that string plus the next four characters, edit it to look like "2017 12-02", and then place that at the beginning of the name.

File name example:

AK_ADVOUTPOSTB1CHARACTER_20171202_406828017946.jpg  
2017 12-02 AK_ADVOUTPOSTB1CHARACTER_406828017946.jpg

If it takes several commands to accomplish that would be fine with me, I'd just like to get this accomplished if possible.

(If you know of a utility that can accomplish this, that would be helpful, too.)

0

1 Answer 1

0

The following Python program will perform these renames.

At the beginning of the program, in the Configuration section, you will need to specify pattern with the year in it (especially when it changes from "2017" to 2018").

If you need to change around the positions of the year/month/day in the filename, these numbers can be changed in the check_and_update function. (The index positions for the string "_20171202" can be accessed using foundAt.start() and foundAt.end()).

#!/usr/bin/env python

import os
import sys
import traceback
import re

# ----------------------------------------------------------------------
# Configuration

# The date string that will be prefixed at the beginning of the file
year_pattern = "_2017[\d]{2}[\d]{2}"

# Only modify files that match this pattern
file_patterns = ["(.*)\.jpg$"]

# Directory to search
start_dirs = ["./"]

# Recursive, check sub-directories
recursive = False

# View the list of modified files, without making any changes
view_modifications_only = True

# ----------------------------------------------------------------------
def add_ending_slash(s):
    suffix = "/"
    if s.endswith(suffix):
        return s
    return s + suffix

# ----------------------------------------------------------------------
def pattern_matches_any(filename, file_patterns):
    progs = []
    for file_pattern in file_patterns:
        progs.append(re.compile(file_pattern))

    for prog in progs:
        if prog.match(filename):
            return True
    return False

# ----------------------------------------------------------------------
def check_all_dirs(start_dirs):
    total_files = 0
    try:
        for start_dir in start_dirs:
            total_files += check_this_dir(start_dir)
    except Exception as e:
        print('*** Caught exception: %s: %s' % (e.__class__, e))
        traceback.print_exc()
    return total_files

# ----------------------------------------------------------------------
def check_this_dir(start_dir):
    total_files = 0

    try:
        for filename in os.listdir(start_dir):
            filepath = os.path.abspath(add_ending_slash(start_dir) + filename)

            # Files
            if os.path.isfile(filepath):
                total_files += check_and_update(start_dir, filename)

            # Directories
            elif recursive and os.path.isdir(filepath):
                total_files += check_this_dir(filepath)
    except PermissionError as e:
        print('*** Caught exception: %s: %s' % (e.__class__, e))
        pass

    return total_files

# ----------------------------------------------------------------------
def check_and_update(start_dir, filename):
    if pattern_matches_any(filename, file_patterns):

        filepath = os.path.abspath(add_ending_slash(start_dir) + filename)

        if (view_modifications_only):
            print("[MATCH]  " + filepath)
        else:
            foundAt = re.search(year_pattern, filename)
            if (foundAt):
                year  = filename[foundAt.end()-8:foundAt.end()-4]
                month = filename[foundAt.end()-4:foundAt.end()-2]
                day   = filename[foundAt.end()-2:foundAt.end()]
                filename_new = year + " " + month + "-" + day + " " + filename[0:foundAt.start()] + filename[foundAt.end():]

                dest = os.path.abspath(add_ending_slash(start_dir) + filename_new)
                print("[UPDATE] " + filepath)
                if (not os.path.isfile(dest)):
                    os.rename(filepath, dest)
                return 1
    return 0

# ----------------------------------------------------------------------
# Main program body
if (view_modifications_only):
    print("[INFO]   This program is being run in \"read-only\" mode.")

print("[START]  The following files will be renamed:")
total_files = check_all_dirs(start_dirs)
print("[END]    File count: " + str(total_files))

print()
input("Press Enter to continue...")
1
  • This program might be a bit more than you are looking for. But I already had something that was reasonably similar to what you wanted, and just had to rework a few parts. Feb 15, 2018 at 19:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .