在Windows下调用shutil.copystat(file1,file2)后,文件修改时间不相等

Ale*_*ler 8 python windows filesystems python-2.7

我用Python 2.7.5运行以下代码.在Windows下:

import os, shutil, stat, time

with open('test.txt', 'w') as f: pass # create an arbitrary file
shutil.copy('test.txt', 'test2.txt') # copy it
shutil.copystat('test.txt', 'test2.txt') # copy its stats, too

t1 = os.lstat('test.txt').st_mtime # get the time of last modification for both files
t2 = os.lstat('test2.txt').st_mtime

print t1 # prints something like: 1371123658.54
print t2 # prints the same string, as expected: 1371123658.54
print t1 == t2 # prints False! Why?!
Run Code Online (Sandbox Code Playgroud)

我希望两个时间戳(=浮点数)相等(正如它们的字符串表示所示),那么为什么要t1 == t2评估False

此外,我无法使用更少的代码重现此行为,即不比较通过os.lstat两个不同文件检索的时间戳.我有这种感觉,我在这里错过了一些微不足道的东西......


编辑:经过进一步测试后,我注意到它True偶尔会打印一次,但不会超过每10次打印一次.


编辑2:正如larsmans所建议的那样:

print ("%.7f" % t1) # prints e.g. 1371126279.1365688
print ("%.7f" % t2) # prints e.g. 1371126279.1365681
Run Code Online (Sandbox Code Playgroud)

这提出了两个新问题:

  1. 调用后为什么时间戳不相等shutil.copystat
  2. print 圆形浮动默认情况下?!

int*_*jay 7

问题在于copystat呼叫期间不同格式之间的转换.这是因为Windows以固定点十进制格式存储文件时间,而Python以浮点二进制格式存储它们.因此,每次在两种格式之间进行转换时,都会丢失一些准确性.copystat通话期间:

  1. 调用os.stat将Windows格式转换为Python的浮点格式.一些准确性会丢失.
  2. os.utime被调用来更新文件时间.这会将其转换回Windows格式.某些准确度再次丢失,文件时间不一定与第一个文件相同.

当您打电话给os.lstat自己时,会执行第三次不准确的转换.由于这些转换,文件时间并不完全相同.

对文件os.utime提到了这一点:

请注意,您在此处设置的确切时间可能不会由后续的stat()调用返回,具体取决于操作系统记录访问和修改时间的分辨率


关于你的第二个问题(为什么print看起来两者都显示相同的值):将浮点值转换为带有str(f)print f将围绕值的字符串.要获得保证对于不同浮点值唯一的值,请print repr(f)改用.