如何获取上次在Python中修改文件的时间?

Bil*_*ard 50 python time file

假设文件存在(os.path.exists(filename)首先使用它确保它存在),如何显示文件上次修改的时间?这是在Linux上,如果这有任何区别.

Jac*_*ack 117

>>> import os
>>> f = os.path.getmtime('test1.jpg')
>>> f
1223995325.0
Run Code Online (Sandbox Code Playgroud)

自(epoch)开始

  • 我不知道这有明确的功能.我想,生活和学习. (5认同)
  • 我也不; 在我的代码库中用`os.path.getmtime`替换`os.stat`的时间...... (4认同)
  • 可能是更便携的解决方案 (2认同)

Dou*_*der 57

os.stat()

import os
filename = "/etc/fstab"
statbuf = os.stat(filename)
print("Modification time: {}".format(statbuf.st_mtime))
Run Code Online (Sandbox Code Playgroud)

Linux不记录文件的创建时间(对于大多数文件系统).


Bri*_*man 12

python 3.4+的新功能(参见:pathlib)

import pathlib

path = Path('some/path/to/file.ext')
last_modified = path.stat().st_mtime
Run Code Online (Sandbox Code Playgroud)

  • pathlib 旨在提供一种面向对象的方法,用于获取 os 和 stat 中的许多功能。它不是为了取代而是为了共同生活。此外,当您需要传递路径并且想要访问文件信息或直接打开文件时,它会变得更加方便。 (5认同)
  • pathlib 处理相对路径。 (4认同)