Reputation: 59
My task is to read 10 numbers from a ,txt file and then print their sum:
f = open("data.txt", "r")
sumofn=0
for i in range(1, 10):
x = f.readline(i)
x = int(x)
sumofn += x
print(sumofn)
Unfortunately, I get this error:
ValueError: invalid literal for int() with base 10: '\n'
Upvotes: 0
Views: 51
Reputation: 94
Here is the simple solution. If your values are comma separated, you can use the split() method:
f = open("data.txt", "r")
sumofn = 0
for i in range(1, 10):
for x in f.readlines():
x = int(x)
sumofn += x
print(sumofn)
Here is also the split() method. It is used if your values are comma separated and space separated:
f = open("data.txt", "r")
sumofn = 0
for i in range(1, 10):
for x in f.readlines():
y = x.split(',')
for x in y:
x = int(x)
sumofn += x
print(sumofn)
Upvotes: 4
Reputation: 315
Regexp is your best friend
with open('data.txt', 'r') as f:
print(sum([int(i) for i in f.read().split('\n') if i != '']))
btw '\n' means it's a linebreak; the enter you press while writing text file. Because it has '\n' when you read the file.
Upvotes: 0
Reputation: 1646
I guess that your file has int values only because you used conversion int()
. In this case, you can use regex pattern r'\d+'
simply (instead of the r'\d+(\.\d+)?'
) but the following code covers the case that the file contains float values.
import re
result = 0
with open('data.txt', 'r') with f:
line = f.readline()
match = re.search(r'\d+(\.\d+)?', line)
if match:
result += float(match.group())
print(result)
Please give it a shot.
Upvotes: 0