Deleting Unaccessed Files Using Python
My django app parses some files uploaded by the user.It is possible that the file uploaded by the user may remain in the server for a long time ,without it being parsed by the app.
Solution 1:
Check out time.time(). It will allow you to access the current timestamp, in utc time. You can then subtract the current stamp from the file timestamp and see if it's greater than 24*60*60.
http://docs.python.org/library/time.html#time.time
Also, keep in mind that a lot of the time, a Linux filesystem is mounted with noatime, meaning the st_atime variable might not be populated. You should probably use st_mtime, just to be safe, unless you're 100% sure the filesystem will always be mounted with atimes recorded.
Here's what should be a working example, I haven't debugged though.
import os
import time
dirname = MEDIA_ROOT+my_folder
filenames = os.listdir(dirname)
filenames = [os.path.join(dirname,filename) for filename in filenames]
for filename in filenames:
last_access = os.stat(filename).st_mtime #secs since epoch
timediff = time.gmtime() - last_access
print filename+'----'+timediff
if timediff > 24*60*60:
print'older than a day'
# do your thing
Solution 2:
Why bother with actual dates? Just check whether os.stat(filename).st_atime < time.time() - 24*60*60.
Post a Comment for "Deleting Unaccessed Files Using Python"