How to get file creation & modification date/times in Python?

前端 未结 13 2196
抹茶落季
抹茶落季 2020-11-21 11:44

I have a script that needs to do some stuff based on file creation & modification dates but has to run on Linux & Windows.

13条回答
  •  Happy的楠姐
    2020-11-21 12:14

    There are two methods to get the mod time, os.path.getmtime() or os.stat(), but the ctime is not reliable cross-platform (see below).

    os.path.getmtime()

    getmtime(path)
    Return the time of last modification of path. The return value is a number giving the number of seconds since the epoch (see the time module). Raise os.error if the file does not exist or is inaccessible. New in version 1.5.2. Changed in version 2.3: If os.stat_float_times() returns True, the result is a floating point number.

    os.stat()

    stat(path)
    Perform a stat() system call on the given path. The return value is an object whose attributes correspond to the members of the stat structure, namely: st_mode (protection bits), st_ino (inode number), st_dev (device), st_nlink (number of hard links), st_uid (user ID of owner), st_gid (group ID of owner), st_size (size of file, in bytes), st_atime (time of most recent access), st_mtime (time of most recent content modification), st_ctime (platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows):

    >>> import os
    >>> statinfo = os.stat('somefile.txt')
    >>> statinfo
    (33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
    >>> statinfo.st_size
    926L
    >>> 
    

    In the above example you would use statinfo.st_mtime or statinfo.st_ctime to get the mtime and ctime, respectively.

提交回复
热议问题