pythonfilelastaccesstime

Why does the last access time change for a file when it gets stored in a list or object?


I'm trying to look at a directory and determine the last time a file was accessed so that I can move files that have an accesstime older than say like a month, but I am having issues with checking the access time of the files. The issue that I seem to be over writing the access time of the file when that is not what I am wanting to do. Why does this happen?

This is for checking file access times and comparing them to say a time frame of a month ago (obviously not done since I am having issues). I've tried using st_mtime and st_ctime, but those don't return the last time a file was accessed. The computer that I am coding this on is a Mac.

import os, shutil
import datetime as dt

downloads = "/Users/tomato/Downloads/"
os.chdir(downloads)

# list of files in downloads or specified directory
files_list = []

class file:
    def __init__(self, object):
        self.object = object
    def getLastATime(self): # prints out something that looks like this: 2019-04-03 which can be read as year-month-day
        return dt.date.fromtimestamp(os.stat(".").st_atime)

for files in os.listdir(os.getcwd()):
    files_list.append(file(files))
print(files_list[0].getLastATime())

My expected results for this when it prints out the first file in the directory is to see 2019-04-02, but what I get is 2019-04-04 which is today and not the last time I went to the file and actually opened it to view or use it.


Solution

  • Your class calls os.stat("."). This will always get the stats of the current directory, not of the file the object was constructed with. (And because you've just accessed the directory with os.listdir(), the access time will be the current time.) Consider using os.stat(self.object) instead.

    Also, don't call your class file. You're going to confuse people who are used to the file class from Python 2.