4

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?

honeymoon
  • 2,400
  • 5
  • 34
  • 43

1 Answers1

16

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • This works only if I open the file in the explorer but not in the Python code... – honeymoon May 09 '13 at 14:47
  • In that case the OS is only updating the access time under certain circumstances that Python doesn't trigger. If the `atime` value is not updated, there is no other metric that shows you when a file was last accessed. What platform is this, Windows? – Martijn Pieters May 09 '13 at 14:51
  • No, Linux (Ubuntu 12.04) but the program must run cross platform. Up to now I solved this by saving the file name into a new file but I found it not so nice. Maybe this is the only way... – honeymoon May 09 '13 at 14:57
  • 1
    @snowflake: see [Wikipedia](http://en.wikipedia.org/wiki/Stat_%28system_call%29#Criticism_of_atime), you are running a Linux system with `relatime` enabled. `atime` is only updated once every 24 hours in that case. – Martijn Pieters May 09 '13 at 14:58
  • Mmmm, thanks Martijn. – honeymoon May 09 '13 at 15:01
  • Thanks for editing your answer. This worked on my personal PC, however I don't want to change those settings from users of my software, so I will stay with saving the file name into another file. Good to know! – honeymoon May 09 '13 at 15:16