How To Archive Files By Date In Python

In my daily work, I always use the data directory to save received files. It is not easy to judge whether the received files are missing or not when there are too many files in the data directory, and it is also not easy to find the files which I want in those so many files. So I wrote a python script, which is executed by windows schedule at 9:00 AM every day to archive all the files received yesterday to an archive folder. The name of the archive folder is yesterday’s date. Below are the python script and explanation.

# Import python os, datetime and shutil module.
import os
import datetime
import shutil
 
'''
  Get a date string with format 'YYYYMMDD'
'''
def get_datetime(i):
    d = str((datetime.datetime.now() - datetime.timedelta(days=i)).date()).split("-")
    timeoffile = d[0] + d[1] + d[2]
    return(timeoffile)
 
''' 
    Get the new archived folder name and path.
'''
def get_archieved_folder(i):
    # Call get_datetime function to get the archieved folder name.
    filename = get_datetime(i)

    # Build the archieve folder path.
    aimPath = 'C:\\data\\' + filename
    
    # Check whether the archieved folder exists or not by it's path. 
    isExists=os.path.exists(aimPath)

    # If the folder does not exist.
    if not isExists:
        # Create the folder and return the folder path.
        os.makedirs(aimPath)
        print(aimPath + 'ok!')
        return aimPath
    else:
        print(aimPath + 'file is exists!')
        return False
 
'''
 After achieve the received files by move them to a archieved folder, delete the files in the original directory.
'''
def delete_flie(filePath):
    for i,j,k in os.walk(filePath):
        n = 0
        while n < len(k):
            fileneed = filePath + '\\' + k[n]
            # If the original file exist then remove it.
            if(os.path.exists(fileneed)):
                os.remove(fileneed)
            else:
                pass
            n = n + 1
     
'''
  Get all the file name in the original data folder and move them to the new archieved folder.
'''
def archieve_files(srcFilePath, archievedFolderPath):
    for i,j,k in os.walk(srcFilePath):
        n = 0
        while n < len(k):
            fileneed = srcFilePath + '\\' + k[n]
            # Use os.path.exists to check whether the file to be moved exist or not before moving it.
            if(os.path.exists(fileneed)):
                # shutil.copy will change the file generation time, it is not easy to check the file received time, so use shutil.move to move file which will not change the file create time.
                shutil.move(fileneed,archievedFolderPath)
            else:
                pass   
            n = n + 1
 
'''
 On Monday, you need to put the files received of Friday, Saturday and Sunday in the folder named after the date of Friday, so use this function to determine the day of the week
'''
def is_monday():
    if datetime.datetime.now().weekday() == 0:
        return 3
    else:
        return 1

# The folder which is used to save the received files. 
srcFilePath = 'C:\\data'

# Check whether today is monday.
pos = is_monday()

# Get the archieved folder by date.
archievedFolderPath = get_archieved_folder(pos)

# Move all the files in the original saved folder to the archieved folder.
archieve_files(srcFilePath, archievedFolderPath)

# Remove the archieved files from original saved folder.
delete_flie(srcFilePath)

https://www.jb51.net/article/205073.htm

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.