Python get last reading time of a file [duplicate]

旧巷老猫 提交于 2019-12-12 09:19:36

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/16464228/python-get-last-reading-time-of-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!