2014-01-28 51 views
0

當我運行下面的代碼而不是輸出文本時,它只顯示一個新行。Python中沒有行輸出

f = open('log.txt', 'a+') 

nick = raw_input('Choose a nickname: ') 
print('Your nickname is now ' + nick) 


f.write(nick + ' has joined the room.\n') 
print f.read() 

當我在log.txt中查看時,它有正確的文本。

回答

0

當您打開一個文件爲"a+"時,您將計算機專門指向文件的最後一行並告訴它「從這裏開始閱讀」。這就是爲什麼你可以附加到它的原因,因爲它不會從最後開始寫任何東西。

這也是爲什麼叫f.read()找不到任何東西。如果您有文字:

File: foo.txt 
Body: 
Nick has joined the room. 
Dave has joined the room. 
Sally has joined the room. 

但是,當你打開文件,你上次月經後打開它,你會讀到的是:

'' 

爲了解決這個問題,使用seek

f = open('foo.txt','a+') # better to use a context manager! 
f.write("bar.\nspam.\neggs.") 
f.read() 
>> '' 
f.seek(0) # moves the pointer to the beginning of the file 
f.read() 
>> bar. 
>> spam. 
>> eggs. 
+0

如何避免這種情況,並打開文件以從頂部追加和讀取?或者我必須打開它,寫信給它,然後關閉並再次打開它來閱讀它? –

+0

@ayoungpythoner我編輯了我的答案。 –

1

發生這種情況,因爲當你寫這樣的文件,它留下的指針指向文件的結尾,所以當你做f.read()它只會顯示在末尾的空白處該文件(在「nick +」加入房間之後。\ n'「)。

在打印語句前添加行:f.seek(0)。 (這會使指針回到最初的位置,0可以替換爲指針開始的任何位置)