2014-07-26 77 views
1

運行此:爲什麼在python中調用file.read填充垃圾文件?

import os 

if __name__ == '__main__': 
    exclude = os.path.join(
     r"C:\Dropbox\eclipse_workspaces\python\sync\.git", "info", "exclude") 
    with open(exclude, 'w+') as excl: # 'w' will truncate 
     # print excl.read() # empty 
     # excl.readall() # AttributeError: 'file' object has no attribute 
     # 'readall' -- this also I do not understand 
     excl.write('This will be written as expected if I comment the 
     line below') 
     print "Garbage\n\n", excl.read() 
    # if I do not comment the line however, the file contains all the garbage 
    # excl.read() just printed (edit: in addition to the line I wrote) 

成果填補我的文件與垃圾 - 爲什麼?另外爲什麼readall沒有解決?

的Python 2.7.3

最新迭代:

#!/usr/bin/env python2 
import os 

if __name__ == '__main__': 
    exclude = os.path.join(r"C:\Users\MrD","exclude") 
    with open(exclude,'w+') as excl: 
     excl.write('This will be written if I comment the line below') 
     print "Garbage\n\n",excl.read() 
    # now the file contains all the garbage 
    raw_input('Lol >') 
+1

爲什麼你期望有'.readall()'方法? –

+0

你能向我們展示你看到的'垃圾'嗎?因爲你的文件指針位於文件的末尾,而'excl.read()'在那一點上返回一個空字符串。 –

+0

@MartijnPieters:Pycharm解決了這個問題 –

回答

5

你已經打在I/O是在C級實施方式的特徵模擬。當您在+模式下打開文件(在您的案例中進行寫入和讀取)時,您的必須在「切換」模式之前發出刷新或尋道,否則行爲未定義。在這種情況下,您將未初始化的內存添加到文件中。

有這個在Python問題跟蹤報告:http://bugs.python.org/issue1394612

的解決辦法是尋求回至開始,如果你想讀回你所寫的內容:

with open(exclude,'w+') as excl: 
    excl.write('This will be written if I comment the line below') 
    excl.seek(0) 
    print "No more garbage\n\n", excl.read() 

你也可以使用同花:

with open(exclude,'w+') as excl: 
    excl.write('This will be written if I comment the line below') 
    excl.flush() 
    print "No more garbage, eof so empty:\n\n", excl.read() 
+0

Ahaha補充說,我是一個蟒蛇新手,你可以想象我的奇蹟的深度 –

+0

而我只是想調試打印ahahaha - 不錯 –

+0

順便說一句,內存初始化 - 當第一次發生時,我看到了非常文件我正在運行在垃圾+ .git/config - 我以爲我失去了它:D –

相關問題