0

I have a collection of files that I would like to re-organize in a smart way, using python. The files are state-county-year specific and saved in a folder structure of this form: \state\year\county\image.jpg with many images per county. I have the following code that copies and renames all files as state_year_county_image.jpg:

import os, shutil
path = "C:\\Users\\me\\"
path_copies = "C:\\Users\\me\\copies\\"
state_list = os.listdir(path)
for state in state_list:
    year_list = os.listdir(path+state)
    for year in year_list:
        county_list = os.listdir(path+state+"\\"+year)
        for county in county_list:
            image_list = os.listdir(path+state+"\\"+year+"\\"+county)
            for image in image_list:
                path_old = path+state+"\\"+year+"\\"+county+"\\"+image
                path_new = path_copies+state+"_"+year+"_"+county+"_"+image
                shutil.copy(path_old, path_new)

How can I change my file naming regime later on (e.g. from the current state_year_county_image.jpg to year_state_county_image.jpg or according to some other naming regime that I may later need)? I would be open to adopting some other basic naming convention if it allows more flexibility, but I would like the filenames to reflect the original folder names.

Julius
  • 1
  • 1
  • 2
    Why are you renaming the files in first place? From your description I assume that you have really many images, placing them all in one folder will make it more difficult to find the files. As long as it is unambiguous which part of the file name is the state, county, year etc. there is no problem with later renaming. You should also consider to use some photo management software where you can assign tags to images. – Pyfisch Jun 06 '16 at 15:22

2 Answers2

0

os.walk could be what you're looking for. Also, I'd recommend not moving your images inside of your search directory, as that'll lead to confusion on re-processing.

Something like this:

import os
import shutil

SRCDIR = r'C:\Users\me\originals'
DESTDIR = r'C:\Users\me\copies'

for dirname, dirs, files in os.walk(SRCDIR):
    dname = dirname.replace(os.path.sep, '_')
    for file in files:
        shutil.copy(file, os.path.join(DESTDIR, 
                                       "{}_{}".format(dname, file))
0

This is essentially the same question as Rename files to instead being in sub-directories, have the year as part of the filename

I suggest you use that pseudo-code, but a new pattern and expression for the filename. You need to provide put some of your actual filenames into Regex101 to make your pattern, and need to decide on your output format.

Charles Merriam
  • 19,908
  • 6
  • 73
  • 83