2020/04/01

File Handling with Python

This little utility is for copying files from source to target directories.  On the way it checks whether a directory exists in the target, if not creates and then copies the files.

import os, time, shutil
from datetime import date
sourceDirHome = "F:\DCIM"
TargetDirHome = 'E:\Personnel\Photos'

for dirName, subdirList, fileList in os.walk(sourceDirHome):
    print("Found Directory",dirName)
    #break
    for f in fileList:
        print("File name is:",f)
        fName = os.path.join(dirName,f)
        print(fName)
        ctime = (os.path.getctime(fName))
        print("Created On", ctime)
        fmtTimeYM = time.strftime('%Y-%m',time.localtime(ctime))
        fmtTimeY = time.strftime('%Y', time.localtime(ctime))
        fmtTimeM = time.strftime('%m', time.localtime(ctime))
        print('formatted time: ',fmtTimeYM)
        tgtpthstrY = os.path.join(TargetDirHome,fmtTimeY)
        tgtpthstrYM = os.path.join(tgtpthstrY,fmtTimeYM)
        if os.path.exists(tgtpthstrYM):
            print(tgtpthstrYM, 'Exists.. copying... 1')
            shutil.copy(fName,tgtpthstrYM)
        else:
            if os.path.exists(tgtpthstrY):
                print(tgtpthstrYM, 'Does Not Exists.. creating... 2')
                os.mkdir(fmtTimeYM)
                shutil.copy(fName, tgtpthstrYM)
            else:
                print(tgtpthstrY, 'Does NOt Exists.. creating... 3')
                os.mkdir(tgtpthstrY)
                os.mkdir(tgtpthstrYM)
                shutil.copy(fName, tgtpthstrYM)

No comments:

Post a Comment

File Handling with Python

This little utility is for copying files from source to target directories.  On the way it checks whether a directory exists in the target, ...