私はS.O.にこの質問についての2つの投稿があることを知っています。彼らは私の問題を解決する助けにはなりませんでした。私はアキュムレータを使用してテキストファイルの値を合計しようとしています。各行に数字がある場合、私のコードはファイル内の各行を表示します。間に空白があると、エラーメッセージが表示されます。私はそれが単純な見落としだと思うが、私はPythonには新しいので、私は何が間違っているのか分からない。Pythonでテキストファイルの値をどのように集計しますか?
マイコード:
def main():
#Open a file named numbers.txt
numbers_file = open('numbers.txt','r')
#read the numbers on the file
number = numbers_file.readline()
while number != '':
#convert to integer
int_number = int(number)
#create accumulator
total = 0
#Accumulates a total number
total += int_number
#read the numbers on the file
number = numbers_file.readline()
#Print the data that was inside the file
print(total)
#Close the the numbers file
numbers_file.close()
#Call the main function
main()
テキストファイル内の
入力:テキストファイル内
100
200
300
400
500
Gives me error message:
ValueError: invalid literal for int() with base 10: '\n'
入力:
100
200
300
400
500
Prints:
100
200
300
400
500
'number'はまだ空行に改行' \ n'を含んでいるので空ではありません。 – AChampion