Python获取文件的最后读取时间 [英] Python get last reading time of a file
问题描述
我正在寻找一种解决方案来获取最后读取文件的时间.该文件不会被修改或创建,只是在阅读模式下打开.这有效,但仅适用于写入文件.如果我以读取模式打开文件,时间不正确:
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)
有什么提示吗?
推荐答案
您正在查看 stat
结构中的错误条目.您想改用 .st_atime
值:
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)
来自 os.stat()
文档:
From the os.stat()
documentation:
st_atime
- 最近访问的时间,
st_atime
- time of most recent access,
请注意,并非所有系统都会更新 atime
时间戳,请参阅 对 atime 的批评.从 2.6.30 开始,Linux 内核默认使用 relatime
设置,其中 atime
值仅在超过 24 小时后更新.您可以通过在 fstab
中设置 strictatime
选项来改变这一点.
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 还禁用了对 atime
的更新,但您可以重新启用它们.
Windows Vista also disabled updates to atime
, but you can re-enable them.
这篇关于Python获取文件的最后读取时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!