我在生成錯誤輸出的代碼中遇到了問題。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
您遇到的實際問題是什麼?考慮到換行符,該輸出對我來說看起來是正確的。 – kindall
問題是字符的長度。例如,嗨的長度應該是2.我將如何擺脫新的行字符? – steve