2017年8月14日 星期一

[ Python 常見問題 ] How to get file creation & modification date/times?

Source From Here 
Question 
I have a script that needs to do some stuff based on file creation & modification dates but has to run on Linux & Windows. What's the best cross-platform way to get file creation & modification date/times in Python? 

How-To 
Getting some sort of modification date in a cross-platform way is easy - just call os.path.getmtime(path) and you'll get the Unix timestamp of when the file at path was last modified. Getting file creation dates, on the other hand, is fiddly and platform-dependent, differing even between the three big OSes: 
* On Windows, a file's ctime (documented at https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx) stores its creation date. You can access this in Python through os.path.getctime() or the .st_ctime attribute of the result of a call to os.stat(). This won't work on Unix, where the ctime is the last time that the file's attributes or content were changed. 
* On Mac, as well as some other Unix-based OSes, you can use the .st_birthtime attribute of the result of a call to os.stat(). 
* On Linux, this is currently impossible, at least without writing a C extension for Python. Although some file systems commonly used with Linux do store creation dates (for example, ext4 stores them in st_crtime) , the Linux kernel offers no way of accessing them; in particular, the structs it returns from stat() calls in C, as of the latest kernel version, don't contain any creation date fields. You can also see that the identifier st_crtime doesn't currently feature anywhere in the Python source. At least if you're on ext4, the data is attached to the inodes in the file system, but there's no convenient way of accessing it.

Putting this all together, cross-platform code should look something like this: 
  1. import os  
  2. import platform  
  3.   
  4. def creation_date(path_to_file):  
  5.     """  
  6.     Try to get the date that a file was created, falling back to when it was  
  7.     last modified if that isn't possible.  
  8.     See http://stackoverflow.com/a/39501288/1709587 for explanation.  
  9.     """  
  10.     if platform.system() == 'Windows':  
  11.         return os.path.getctime(path_to_file)  
  12.     else:  
  13.         stat = os.stat(path_to_file)  
  14.         try:  
  15.             return stat.st_birthtime  
  16.         except AttributeError:  
  17.             # We're probably on Linux. No easy way to get creation dates here,  
  18.             # so we'll settle for when its content was last modified.  
  19.             return stat.st_mtime  


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...