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

时间:2014-01-26 16:38:58

标签: 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:\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, '

由于

答案:

file = open("C:\\Users\\Dylan\\Python\\OddNumbersAns.txt", "r")

line = file.read()

line.split(",")

print (line.split(","))

total = sum([int(num) for num in line.split(',')])

print(total)

3 个答案:

答案 0 :(得分:2)

在每个逗号分隔行后,你需要sum()函数:

total = sum(int(num) for num in line.split(','))

不要试图调用int(line),因为它试图将整行转换为单个int。

相反,您在每个逗号上拆分行,产生一系列字符串,每个字符串都转换为int。将整个函数放在sum函数中将它们组合在一起。

答案 1 :(得分:0)

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

#a.txt
1, 3, 5, 7, 9, 11, 13, 15, 
2, 3, 45, 6,

您需要先strip,然后split

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('')会引发ValueError。

答案 2 :(得分:0)

这是你需要的基本内容

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