2015-11-14 35 views
0

爲什麼當我運行下面的代碼時,Python總是打印額外的換行符?我試圖重新編寫代碼以消除任何意外的空白,但它仍然會打印出一個額外的新行。有人知道爲什麼謝謝。Python打印不需要的額外換行符

def main(): 
    names_in()       #This function import the file and read all the content and put the content into a list. 

    print_names(names_in)  # Before the names are sorted. 

def names_in(): 
    infile = open('names.txt','r') 
    names_list = []     #empty list. 
    names = infile.readline() # read contents. 

    #loop for continue to read. 
    while names != '': 
     names = infile.readline()  #continue to the next name. 
     names = names.rstrip('\n') #return a copy of the string which all \n has been stripped from the end of the string. 
     names_list.append(names) #write names in the file into a list. 
    infile.close() 

    return names_list      #return the list back to the function. 



def print_names(names_in):  #This function will print out the names in the list one per line, single-spaced. 
    for item in names_in(): 
     print(item) 


main() 

這在我的輸入文件:

Riggs, Jerry 
Stone, Ruby 
Wood, Holly 
Dover, Ilene 
Funt, Ella 
Storm, Wayne 
Lowe, Lyle 
Free, Bjorn 
Caine, Candy 
Carr, Rex 
Downs, Mark 
Twain, Lionel 
Thorn, Rose 
Shore, Rocky 
Bush, Rose 
Waters, Muddy 
Graves, Doug 
Stone, Roxanne 
Rivers, Wade 
+1

您讀取輸入文件兩次;如果'print_names()'再次調用它,則不需要先調用'names_in()'並放棄結果。 –

回答

1

你的代碼打印額外的換行符的原因是因爲在names_in功能的最後一次迭代中,變量names是``,它被附加到names_list的末尾,導致print_names函數在最後運行print '',這會打印一個額外的換行符。

+0

謝謝你的解釋。無論如何我可以解決這個問題嗎?我不知道如何修改循環,以便它可以讀取文件中的每一行,並且不會同時打印額外的換行符。 –