1

I wish to write a python script which deletes files which weren't accessed in >= x days. I know I can check when the file was created and when it was modified, but can I somehow check when it was last accessed ?

Thanks, Li

user429400
  • 3,145
  • 12
  • 49
  • 68
  • Check here for how to get the "last access time" of a file: https://stackoverflow.com/questions/14393744/get-last-access-time-of-the-file – IoaTzimas May 04 '21 at 09:35

1 Answers1

2

You can check when the file was last opened using 'stat', Check how much time has passed using 'time', And delete it using 'os':

import os
import stat
import time

fileStats = os.stat(filePath)
last_access = fileStats[stat.ST_ATIME] # in seconds
now = time.time() # in seconds
days = (now - last_access)  / (60 * 60 * 24) 
# The seconds that have elapsed since the file was last opened are divided by the number of seconds per day 
# this give the number of days that have past since the file last open

if x <= days:
  # we delete the file
    os.remove(filePath)
  
EyaS
  • 477
  • 3
  • 9