【问题标题】:python beginner: reading a file and adding its integerspython初学者:读取文件并添加其整数
【发布时间】:2015-11-25 05:12:59
【问题描述】:

所以我试图从文件 numbers.txt 中提取数字并将它们加在一起。该程序目前可以一次拉出一个数字并将它们间隔打印在一行上。我现在需要它来汇总所有值。文件中的数字是:9 19 15 17 5 和 17。总数应该是 82 但它只会添加两个数字 17 并输出 34。

def main():

numfile = open('numbers.txt', 'r')
total = 0
for line in numfile:
    line = line.rstrip('\n')

    print (line, end=' ')
    total = int(line)
    total += total

print ("\nEnd of file")   
print (total)

numfile.close()

main()

【问题讨论】:

    标签: file integer add


    【解决方案1】:

    当你执行代码 total = int(line) - 主要错误 - 重置总的值

    In [11]: numfile = open('numbers.txt', 'r')
    
    In [12]: total = 0
    
    In [13]: for line in numfile:
       ....:     line = line.strip()
       ....:     print line,
       ....:     total += int(line)
       ....:
    9 19 15 17 5 17
    
    In [14]: total
    Out[14]: 82
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      • 2012-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多