我正在处理从文件中读取数据的作业。我试图总结文件中的所有偶数,但我不能让它读取超过第一行的数字。这是我到目前为止的代码:
infile = open('data.txt', 'r')
even_sum = 0
line = infile.readline()
while int(line) % 2 == 0:
even_sum += int(line)
line = infile.readline()
infile.close()
print('Sum of even numbers: ' + str(even_sum))
答案 0 :(得分:3)
假设每一行只包含一个数字而不是多个数字:
with open('data.txt') as infile: # using `with open()` you do not need to do `infile.close()`, that is done for you.
even_sum = 0
for line in infile: # Iterate over the lines
num = int(line) # Avoid calling int() multiple times if you can.
if num % 2 == 0: # Its an even number.
even_sum += num
print('Sum of even numbers: ' + str(even_sum))
单行使用sum()
只是为了咯咯笑:
print('Sum of even numbers: ' + str(sum([int(l) for l in open('data.txt') if int(l) % 2 == 0])))
答案 1 :(得分:1)
你的while循环进入无限循环,你错过了迭代文件: 这是解决方案:
def sum_even():
with open('test1.txt') as input_file:
# Looping through the file line by line
even_sum = 0
for line in input_file:
if int(line) % 2 == 0:
print line
even_sum += int(line)
print('Sum of even numbers: ' + str(even_sum))
if __name__ == "__main__":
sum_even()