我使用Python 2.7.5運行以下代碼。在Windows下:在Windows下調用shutil.copystat(file1,file2)後文件修改時間不相等
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?!
我以爲這兩個時間戳(=浮動)相等(因爲它們的字符串表示建議),所以爲什麼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
這就提出了兩個新問題:
- 爲什麼時間戳沒有要求
shutil.copystat
後平等的嗎? print
輪默認浮動?!
無法在Debian Linux上重現。嘗試'print(「%。7f」%t1)'和'(t1-t2)<1e-4'來查看「小字體」是否不同。 –
要了解爲什麼默認情況下打印循環是浮動的,試試這個:'x = 10.1(newline)print(「%.20f」%x)'。這會打印出你認爲不同的東西。這是正常的,因爲浮點值不能完全表示所有小數值。儘管如此,我並不知道這個問題。 –
我知道二進制表示,但這裏的情況是不同的:我們有一個值爲「10.099999」的浮點數,雖然我們沒有指定諸如「%.2f」之類的格式,但它打印的是'10.1' - 所以似乎有一個隱含的四捨五入效果,我不知道,我從來沒有觀察過...... –