0

I am trying to archive existing file apart from the latest modified file in Python or FME. I have managed to get it to point where I can get python pick up the latest modified file but any ideas on how I can archive all the files i have in my folder apart from the last modified file?

Thank You

cardiokhan
  • 29
  • 6
  • 1
    could you show an example directory, what it looks like before and the expected outcome? – SRT HellKitty Nov 04 '19 at 18:37
  • A simple directory, do you mean like file path? D:\Documents\test = where the files appear on daily basis. You will for example have 10 files in there. I would like to move them to D:\Documents\archive 9 of the files out of 10. Keep the latest date modified file. – cardiokhan Nov 04 '19 at 18:40
  • does this help? https://stackoverflow.com/questions/8858008/how-to-move-a-file-in-python – SRT HellKitty Nov 04 '19 at 18:48
  • Thanks. Just had a look, there is possibly some of it which helps but unsure if there is anyway where it can pick up the latest file only and archives the rest of the files. – cardiokhan Nov 04 '19 at 19:06
  • You can use [os.path.getmtime](https://docs.python.org/library/os.path.html#os.path.getmtime) to find the times and pick the most recent and move all the others? I can make an answer if this sounds like it would work. – SRT HellKitty Nov 04 '19 at 19:10
  • That may work. I can adjust it if it does play up. – cardiokhan Nov 04 '19 at 19:21

1 Answers1

0

You can solve your problem using this snippet of code:

import glob
import os
import zipfile

files_dir = r'C:\Users\..\files' # here should be path to directory with your files
files = glob.glob(files_dir + '\*')
# find all files that located in specified directory
files_modify_dt = [os.path.getmtime(file) for file in files]
# take files except last modified file
files_to_zip = [file for _, file in sorted(zip(files_modify_dt, files))][:-1]
# zip of selected files
with zipfile.ZipFile(os.path.join(files_dir, 'archive.zip'), 'w', zipfile.ZIP_DEFLATED) as zip_obj:
    for file in files_to_zip:
        zip_obj.write(file, os.path.basename(file))
        os.remove(file)
Eduard Ilyasov
  • 3,268
  • 2
  • 20
  • 18