Is it Possible through python or with any other language to archive the daily downloaded files into one folder

146 Views Asked by At

I need a utility to archive my daily downloaded files into one new folder.

Suppose, I downloaded 10 files today and at the end of the day, all the files should get archived into one new folder with name Archived_TodaysDate.

THIS ACTIVITY/TASK CAN BE SCHEDULABLE AND EXECUTE ON DAILY BASIS.

IT WOULD BE GOOD IF YOU HELP IN THE CONTEXT OF MAC OPERATING SYSTEM.

I know this can be done through many scripting languages but I wanted to know for mac which scripting language is good for this task and a quick start guide.

1

There are 1 best solutions below

0
Charles Landau On

If you aren't familiar with setting up a chrontab you can set those up by following this (I looked for a mac-specific one but there are zillions of guides about this.)

Your archiving script can be quite simple. Begin by generating a list of files to archive (refer to this answer.)

import datetime as dt
import time
import os
import zipfile

now = dt.datetime.now()
ago = now-dt.timedelta(days=1)

Unlike in the referenced answer we want a list of files, not a printed output. So we initialize a list and append to it at each iteration. Here I assume that your script lives in your downloads folder, but you can change the path given to os.walk as appropriate.

to_archive = []

for root, dirs,files in os.walk('.'):  
    for fname in files:
        path = os.path.join(root, fname)
        st = os.stat(path)    
        mtime = dt.datetime.fromtimestamp(st.st_mtime)
        if mtime > ago:
            to_archive.append(path)

We also want a strftime representation of now for our archive file title.

ts = now.strftime("%m_%d_%Y")

Finally write the files into an archive file (in this case I chose zip format).

with zipfile.ZipFile('{}_archive.zip'.format(ts), 'w') as myzip:
    for x in to_archive:    
      myzip.write(x)