2014-01-21 25 views
0

我一直在學Python幾天(以前從未學會編程),我正在閱讀Learn Python The Hard Way。我目前正在練習16,我對此沒有多少嘗試,但我需要一點幫助。當我執行腳本並寫入所有被要求的三行時,它讀取前兩行輸入的內容,當它讀取行時,它們之間有空格。這是腳本:Python readline輸出總是在打印的文本之間留下空白

from sys import argv 

script , filename= argv 

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

print "Now I'm going to ask you for three lines." 

line1 = raw_input("line 1: ") # first input 
line2 = raw_input("line 2: ") # second input 
line3 = raw_input("line 3: ") # third input 

print "I'm going to write them down and read them later." 

target.write(line1 + "\n" + line2 + "\n" + line3) 

target.close() 

krc = open(filename , "r") 
print "Reading the lines now \n%s \n%s" % (krc.readline() , krc.readline()) 

輸出看起來是這樣的:

Reading the lines now 
line1 
    #<<<< Why is this blank space here?# 
line2 

我希望你明白我的問題(其可能是我缺少一些愚蠢的錯誤)。謝謝。

+0

你是如何運行你的腳本? – wnnmaw

回答

0

\n插入新行。在最後打印的字符串中的每個變量前面都有一個。文件中每行的末尾已經有一個\n,所以它將在它們之間打印一行額外的行。

+0

感謝您的幫助。我刪除了\ n並且現在可以正確打印出來。 – stiffman771

0

readline不會刪除行尾的換行符。您不需要將其他換行符附加到格式字符串中。