我正在为dkfileutils
编写Path.touch测试:
class Path(str):
def touch(self, mode=0o666, exist_ok=True):
"""Create this file with the given access mode, if it doesn't exist.
(based on https://github.com/python/cpython/blob/master/Lib/pathlib.py)
"""
if exist_ok:
# First try to bump modification time
# Implementation note: GNU touch uses the UTIME_NOW option of
# the utimensat() / futimens() functions.
try:
os.utime(self, None)
except OSError:
# Avoid exception chaining
pass
else:
return
flags = os.O_CREAT | os.O_WRONLY
if not exist_ok:
flags |= os.O_EXCL
fd = os.open(self, flags, mode)
os.close(fd)
我尝试了以下各种变体..
def test_touch():
before = time.time()
with open('a', 'w') as fp:
fp.write('a')
after = time.time()
assert before <= after
a = Path('a')
a_before_touch = a.getmtime()
assert before <= a_before_touch <= after
a.touch()
after_touch = time.time()
a_after_touch = a.getmtime()
assert a_before_touch <= a_after_touch
assert a_after_touch >= after
assert a_after_touch <= after_touch
但它一直失败(https://travis-ci.org/datakortet/dkfileutils/builds),运行68:
> assert before <= a_before_touch <= after
E assert 1489532961.064958 <= 1489532961.064464
运行67
> assert a_after_touch > after
E assert 1489532462.412086 > 1489532462.412933
运行66
> assert a_after_touch > after
E assert 1489532286.6042855 > 1489532286.606766
假设time.time()和file.getmtime()是相关的,我真的很傻吗?
答案 0 :(得分:2)
所有文件系统仅分配有限数量的位来存储文件时间戳;在一些较旧的文件系统中,分辨率是一秒或更差。一般来说,它永远不会给你与直接读时钟相同的分辨率。