2013-10-14 13 views
2

我在生成錯誤輸出的代碼中遇到了問題。python中的Openfile函數

def main(): 
    count = 1 
    filename = input('Enter filename: ') 
    for lines in open(filename): 
     lines.strip('') 
     print('Total # of characters: ',len(lines)) 
     count = count + 1 
    print('Total number of lines =', count) 
main() 

問題 - 編寫一個程序,讀取文件,words.txt,具有每行一個字,並打印出的字符的總數目和文件中的行的總數。

所以,我的代碼使用count來計算文件中將在最後打印的行數。這個計數工作正常。但是,計數字符是錯誤的。我的輸出...

Enter filename: word.txtEnter filename: word.txt 
Total # of characters: 3 
Total # of characters: 6 
Total # of characters: 5 
Total # of characters: 6 
Total # of characters: 6 
Total number of lines = 5 

的WORD.TXT文件=

hi 
hello 
hiiiiiiii 
herrooo 
herr 
+0

您遇到的實際問題是什麼?考慮到換行符,該輸出對我來說看起來是正確的。 – kindall

+0

問題是字符的長度。例如,嗨的長度應該是2.我將如何擺脫新的行字符? – steve

回答

3

這樣做lines.strip('')你剝只在''

這樣做:

lines = lines.strip() 

strip()會最後也剝離了\n

+2

它應該是'lines = lines.strip()',而不僅僅是'lines.strip()' – karthikr

+0

我在提交之前沒有看到您的編輯。 +1給你忍者編輯 – Andy

+0

也爲了擺脫換行符,'lines.rstrip('\ n')'會更合適。取決於空間是否是用於OP的有效「字符」。 – millimoose

1

您遇到的問題與lines.strip('')一行。通過傳遞一個參數,它將僅在''時剝離該線。另一個問題是你沒有把這個語句分配給任何東西。嘗試將其替換爲

lines = lines.strip()