在文本文件中添加数字(python)

在文本文件中添加数字(python),python,Python,您好,我被赋予一项任务,从文本文件“1,3,5,7,9,11,13,15”中读取这些数字,并将它们加在一起,我该怎么做?到目前为止,我已经: file = open("C:\\Users\\Dylan\\Python\\OddNumbersAns.txt", "r") line = file.read() intline = int(line) print(intline) 但我收到了这个错误: Traceback (most recent call last): File "C:\Use

您好,我被赋予一项任务,从文本文件“1,3,5,7,9,11,13,15”中读取这些数字,并将它们加在一起,我该怎么做?到目前为止,我已经:

file = open("C:\\Users\\Dylan\\Python\\OddNumbersAns.txt", "r")
line = file.read()
intline = int(line)
print(intline)
但我收到了这个错误:

Traceback (most recent call last):
  File "C:\Users\Dylan\Python\text file add.py", line 3, in <module>
    intline = int(line)
ValueError: invalid literal for int() with base 10: '1, 3, 5, 7, 9, 11, 13, 15, '
在每个逗号上拆分行后,需要sum()函数:

total = sum(int(num) for num in line.split(','))
不要试图调用
int(line)
,因为这会试图将整行转换为单个int


相反,在每个逗号上拆分行,生成一个字符串序列,每个字符串都转换为
int
。将所有内容放在sum函数中,将它们相加。

如果文件包含尾随的新行或逗号:

#a.txt
1, 3, 5, 7, 9, 11, 13, 15, 
2, 3, 45, 6,
您需要先
将其剥离
,然后
拆分

In [174]: with open('a.x', 'r') as f:
     ...:     line=f.read()
     ...:     total=sum(map(int, line.strip(', \n').split(',')))
     ...:     print total
#output: 120

如果没有
strip
,例如
'1,2,n'
将被拆分为
['1','2','\n']
,而
int('\n')
int(''')
将产生一个值错误。

这是您需要的基本资料

>>> txt_line = "1, 2, 3, 4, 5, 6, 7, 8"
>>> 
>>> [int(ele.strip()) for ele in txt_line.split(",")]
[1, 2, 3, 4, 5, 6, 7, 8]
>>> sum([int(ele.strip()) for ele in txt_line.split(",")])
36
>>> 
除此之外,您可能还需要处理文件输入 它可以是完整的文件内容,也可以是逐行读取 因此,我建议如下

with open('input_file.txt', 'r') as fp:
    line = fp.readline()
    while line:
        ## Here insert the above logic
        line = fp.readline()

您试图将整行转换为单个整数。您需要首先将其拆分为单独的字符串,并使用逗号。研究
split
函数。您的名字是Dylan吗?不需要列出,您可以这样调用sum:
total=sum(int(num)表示行中的num。split(',)
。性能可能会有所提高+1用于使用
sum
total=sum(map(int,line.split(','))
。即使BDFL不喜欢它,它看起来也更简洁明了。@PauloBu-当然,你是对的。在这里包含列表是多余的;我已经删除了它。
with open('input_file.txt', 'r') as fp:
    line = fp.readline()
    while line:
        ## Here insert the above logic
        line = fp.readline()