This is most compact code I can think of right now:
(updated to handle the n
at the end, thanks, @JonClements!)
with open('file.txt', 'r') as fin:
ans = sum(int(line) for line in fin if line.strip().isnumeric())
For the code structure you have, you can also go for this:
f = open('data.txt', 'r')
ans = 0
for line in f:
try:
ans += int(line.strip())
except ValueError:
pass
Edit:
Since the confusion with the 'n' has been cleared, the first example can be as simple as
with open('file.txt', 'r') as fin:
ans = sum(int(line) for line in fin)
Or even this one-liner:
ans = sum(int(line) for line in open('file.txt', 'r'))
But there are certain risks with file handling, so not strongly recommended.