2014-03-02 67 views
3

我正在嘗試在寫入之後從最初的空文件讀取,然後關閉它。這在Python中可能嗎?在寫入之後從文件中讀取,關閉之前

some_data = "this is a string" 

with open("outfile1.txt", 'r+') as f: 
    print "Writing ..." 
    f.write(some_data) 
    f.flush() 
    print "File contents:" 
    print f.read() 

print "Again ..." 
print open("outfile1.txt", 'r').read() 

法拉盛與f.flush()似乎不起作用,因爲最終還是print f.read()打印什麼。

除了重新打開文件外,還有什麼方法可以從文件中讀取「當前數據」嗎?

回答

4

您需要的文件對象的指數復位到第一位置,USIG seek()

some_data = "this is a string" 

with open("outfile1.txt", 'r+') as f: 
    print "Writing ..." 
    f.write(some_data) 
    f.flush() 
    // "rewind" the fd to the first position 
    f.seek(0) 
    print "File contents :" 
    print f.read() 

這將使該文件可從中讀取

2

尋求回讀取前的文件開始:

f.seek(0) 
print f.read()