我知道在S.O.上有一些关于这个问题的帖子。但他们没有帮助我解决我的问题。我试图使用累加器来总结文本文件中的值。当每行都有一个数字时,我的代码只打印文件中的每一行。当我之间有空格时,我收到错误消息。我认为这是一个简单的疏忽,但我是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
答案 0 :(得分:1)
您需要排除空行,因为您无法将它们转换为int()
。一种pythonic(EAFP)方法是捕获异常并忽略(尽管这会默默地忽略任何非数字行):
with open('numbers.txt','r') as numbers_file:
total = 0
for line in numbers_file:
try:
total += int(line)
except ValueError:
pass
print(total)
或者你可以在.strip()
所有空格后明确测试你没有空字符串(对于非数字行,这仍然是错误的,例如'hello'
):
with open('numbers.txt','r') as numbers_file:
total = 0
for line in numbers_file:
if line.strip():
total += int(line)
print(total)
第二个可以写成生成器表达式:
with open('numbers.txt','r') as numbers_file:
total = sum(int(line) for line in numbers_file if line.strip())
print(total)
答案 1 :(得分:0)
在添加新值之前,每次循环时都会将值0
赋值给累加器。这意味着您每次都会将新值添加到0
,这意味着您只需打印新值。
如果你将行total = 0
移动到循环之前,那么它应该像你希望的那样工作。
如果你愿意,可以稍微清理一下:
numbers_file = open('numbers.txt','r')
total = 0
for number in numbers_file:
if number:
int_number = int(number)
total += int_number
print(total)
numbers_file.close()
将是第一关。如果if number
包含" truthy"则number
支票会返回True。值,在这种情况下,如果你遇到一个空行就会发生。
答案 2 :(得分:0)
嗨,你错过了删除\n
的'新行符号'。
为了确保只获得可以转换为数字的文字,您必须删除其他字符。
例如。
a = '100\ntest'
print(a.isnumeric())
a = '103478'
print(a.isnumeric())
您可以测试是否存在阻止转换为数字的字符。 正则表达式包可以轻松地操作字符串。
请参阅this stack overflow threat。
import re
a = jkfads1000ki'
re.sub('\D','',a)
'1000'
请参阅re
上的the Python docs。