2012-12-31 31 views
1

我目前在閱讀「瞭解Python的難題」,並已到達第16章。
我似乎無法在寫入文件後打印文件的內容。它只是打印什麼。在寫入之後無法讀取文件

from sys import argv 

script, filename = argv print "We are going to erase the contents of %s" % filename print "If you don\'t want that to happen press Ctrl-C" 
print "If you want to continue press enter" 

raw_input("?") print "Opening the file..." target = open(filename, "w") 

print "Truncating the file..." target.truncate() 

print "Now i am going to ask you for 3 lines" 

line_1 = raw_input("Line 1: ") 
line_2 = raw_input("Line 2: ") 
line_3 = raw_input("Line 3: ") 

final_write = line_1 + "\n" + line_2 + "\n" + line_3 

print "Now I am going to write the lines to %s" % filename 

target.write(final_write) 

target.close 

print "This is what %s look like now" %filename 

txt = open(filename) 

x = txt.read() # problem happens here 
print x 

print "Now closing file" 

txt.close 
+3

'target.close'應該是'target.close()'和相反,你應該使用'with'語句。 –

+0

...和'txt.close'應該是'txt.close()' –

+0

並且打開寫入已經截斷。 –

回答

1

你沒有通話功能target.closetxt.close,而是你只是得到他們指針。由於它們是函數(或方法,爲了更加準確),您需要在函數名稱後面調用()file.close()

這就是問題;您以寫入模式打開文件,刪除文件的所有內容。你在文件中寫入,但是你永遠不會關閉它,所以這些修改不會被提交,並且文件保持空白。接下來,您可以在讀取模式下打開它,只需讀取空白文件即可。

要手動提交更改,請使用file.flush()。或者簡單地關閉文件,它會自動刷新。

此外,調用target.truncate()是無用的,因爲它已在write模式下自動完成,如註釋中所述。

編輯:也在評論中提到,使用with語句是相當強大的,你應該使用它。您可以從http://www.python.org/dev/peps/pep-0343/中閱讀更多內容,但基本上與文件一起使用時,它會打開文件並在您取消打印後自動關閉文件。這樣您就不必擔心關閉文件,並且由於縮進,您可以清楚地看到文件的使用位置,因此看起來好多了。

簡單的例子:

f = open("test.txt", "r") 
s = f.read() 
f.close() 

可以做到更短,更好地利用with聲明尋找:

with open("test.txt", "r") as f: 
    s = f.read() 
+0

雖然解決方案是正確的,但解釋不是。 –

+0

現在好了嗎? :-) – 2012-12-31 11:47:04

+0

是的,好多了。 –