Organize Images

Here is a super simple Python script to organize images into the following folder structure
Source Structure
A
–B
—C

Target Structure
2014
–Jan
–Feb

2015
–Jan
–Feb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# move files module
import os, os.path, time, shutil


def move(path, out):    # take a directory
    fileList = []
    print(path)
    fileCount = 0
   
    for (path, dirs, files) in os.walk(path,  onerror=oswalkerr):
        for file in files:
            fileList.append(os.path.join(path, file))
           
       
        fileCount = fileCount + len(files)
   
    print('source directory ' + str(fileCount))  
   
    index = 0;
    for file in fileList:
       var = time.ctime(os.path.getmtime(file))
       year = var[-4:]
       month = var[4:8]
       yearPath = os.path.join(out, year)
       if os.path.exists(yearPath) == False:
           os.mkdir(yearPath)
       
       yearMonthPath = os.path.join(yearPath, month.strip())
       if os.path.exists(yearMonthPath) == False:
           os.mkdir(yearMonthPath)
           
       
       newFile = os.path.join(yearMonthPath, os.path.basename(file))
       
       if os.path.exists(newFile) == True:
           newFileMod = os.path.join(yearMonthPath, 'conflict_' + str(index) + '_' + os.path.basename(file))
           os.rename(newFile, newFileMod)
           index = index + 1
           
       
       shutil.move(file, newFile)

    fileCount = 0    
    for (out, dirs, files) in os.walk(out,  onerror=oswalkerr):
        fileCount = fileCount + len(files)
   
    print('target directory ' + str(fileCount))  
   
 
 
def oswalkerr(err):
    print(err)


if __name__ == "__main__":
    import sys
    move(sys.argv[1], sys.argv[2])

Leave a Reply

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