mac系统python读取文件路径_在Mac上使用Python获取文件创建时间

在Mac系统中,Python的os.path.getctime返回的是文件最后修改时间,而非创建时间。但HFS+文件系统确实保存了文件的创建时间。通过os.stat的st_birthtime属性或使用ctypes调用stat64系统函数,可以获取文件的创建时间。另外,也可以利用subprocess模块调用stat命令来获取这一信息。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

Python's os.path.getctime on the Mac (and under Unix in general) does not give the date when a file was created but "the time of the last change" (according to the docs at least). On the other hand in the Finder I can see the real file creation time so this information is kept by HFS+.

Do you have any suggestions on how to obtain the file creation time on the Mac in a Python program?

解决方案

Use the st_birthtime property on the result of a call to os.stat() (or fstat/lstat).

def get_creation_time(path):

return os.stat(path).st_birthtime

You can convert the integer result to a datetime object using datetime.datetime.fromtimestamp().

For some reason I don't think this worked on Mac OS X when this answer was first written, but I could be mistaken, and it does work now, even with older versions of Python. The old answer is below for posterity.

Using ctypes to access the system call stat64 (works with Python 2.5+):

from ctypes import *

class struct_timespec(Structure):

_fields_ = [('tv_sec', c_long), ('tv_nsec', c_long)]

class struct_stat64(Structure):

_fields_ = [

('st_dev', c_int32),

('st_mode', c_uint16),

('st_nlink', c_uint16),

('st_ino', c_uint64),

('st_uid', c_uint32),

('st_gid', c_uint32),

('st_rdev', c_int32),

('st_atimespec', struct_timespec),

('st_mtimespec', struct_timespec),

('st_ctimespec', struct_timespec),

('st_birthtimespec', struct_timespec),

('dont_care', c_uint64 * 8)

]

libc = CDLL('libc.dylib') # or /usr/lib/libc.dylib

stat64 = libc.stat64

stat64.argtypes = [c_char_p, POINTER(struct_stat64)]

def get_creation_time(path):

buf = struct_stat64()

rv = stat64(path, pointer(buf))

if rv != 0:

raise OSError("Couldn't stat file %r" % path)

return buf.st_birthtimespec.tv_sec

Using subprocess to call the stat utility:

import subprocess

def get_creation_time(path):

p = subprocess.Popen(['stat', '-f%B', path],

stdout=subprocess.PIPE, stderr=subprocess.PIPE)

if p.wait():

raise OSError(p.stderr.read().rstrip())

else:

return int(p.stdout.read())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值