2016-11-02 83 views
3

我是新來學習python。我不明白爲什麼打印命令會在屏幕上輸出所有變量,但將寫入命令寫入文件只能寫入前兩個變量。在蟒蛇爲什麼它不會打印沒有換行

print "Opening the file..." 
target = open(filename, 'a+') 

line1 = raw_input("line 1: ") 
line2 = raw_input("line 2: ") 
line3 = raw_input("line 3: ") 
line4 = line1 + "\n" + line2 + "\n" + line3 

# This command prints all 3 (line1,line2,line3) variables on terminal 
print line4 

#This command only writes line1 and line2 variables in file 
target.write(line4) 

print "close the file" 
target.close() 

回答

7

操作系統通常在換行符後刷新寫入緩衝區。 當您使用open(filename, 'a+')文件時,這些相同的規則默認應用。

從文檔:https://docs.python.org/2/library/functions.html#open

可選緩衝參數指定文件的所需的緩衝區 大小:0表示無緩衝,1表示行緩衝,任何其它正 值意味着使用的(大約)的緩衝區大小(以字節爲單位)。 A 負緩衝意味着使用系統默認的,這通常是 線路緩衝用於tty設備並且完全緩衝用於其他文件。如果省略了 ,則使用系統默認值。

呼叫target.close(),確保一切寫出來(「刷新」)的文件(按照下面的評論,你接近刷新)。您可以手動使用target.flush()進行刷新。

print "Opening the file..." 
target = open(filename, 'a+') 

line1 = raw_input("line 1: ") 
line2 = raw_input("line 2: ") 
line3 = raw_input("line 3: ") 
line4 = line1 + "\n" + line2 + "\n" + line3 

# This command prints all 3 (line1,line2,line3) variables on terminal 
print line4 

target.write(line4) 

target.close() #flushes 

另外,使用with關鍵字時,我們離開with塊將自動關閉文件:(見What is the python keyword "with" used for?

print "Opening the file..." 
with open(filename, 'a+') as target: 

    line1 = raw_input("line 1: ") 
    line2 = raw_input("line 2: ") 
    line3 = raw_input("line 3: ") 
    line4 = line1 + "\n" + line2 + "\n" + line3 

    # This command prints all 3 (line1,line2,line3) variables on terminal 
    print line4 

    target.write(line4) 
+4

'close' autoflushes,所以通常不需要衝洗'你自己。 – user2357112

+2

我想你應該添加一個關於'with'的評論 –

+0

忘了提及我已經包括在最後但它仍然只打印line1和line2變量文件。嘗試'打開(文件名,'+')作爲目標:'但結果相同。任何人都可以在外行解釋這一點。 – user197010