Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
File python初学者:读取文件并添加其整数_File_Integer_Add - Fatal编程技术网

File python初学者:读取文件并添加其整数

File python初学者:读取文件并添加其整数,file,integer,add,File,Integer,Add,所以我试图从一个文件numbers.txt中提取数字,并将它们添加到一起。该程序目前可以一次提取一个数字,并将它们间隔打印在一行上。我现在需要它来合计所有的值。档案中的数字是:9 19 15 17 5和17。总数应该是82,但它只会将两个数字17和输出34相加 def main(): main() 执行代码total=int(line)-Main Error-重置total的值 numfile = open('numbers.txt', 'r') total = 0 for line in nu

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

def main():

main()

执行代码
total=int(line)
-Main Error-重置total的值

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()
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