Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python get last reading time of a file [duplicate]

I'm looking for a solution to get the time a file was read at last. The file will be not modified or created just opened in reading mode. This works but only for writing in a file. If I open the file in read mode, the time is not correct:

f = open('my_path/test.txt', 'r')
f.close()

print time.ctime(os.stat('my_path/test.txt').st_mtime)

Any hints?

like image 425
honeymoon Avatar asked Dec 09 '22 15:12

honeymoon


1 Answers

You are looking at the wrong entry in the stat structure. You want to use the .st_atime value instead:

print time.ctime(os.stat('my_path/test.txt').st_atime)

From the os.stat() documentation:

  • st_atime - time of most recent access,

Note that not all systems update the atime timestamp, see Criticism of atime. As of 2.6.30, Linux kernels by default use the relatime setting, where atime values are only updated if over 24 hours old. You can alter this by setting the strictatime option in fstab.

Windows Vista also disabled updates to atime, but you can re-enable them.

like image 178
Martijn Pieters Avatar answered Dec 11 '22 05:12

Martijn Pieters