-1

I have a file that has only numbers on each line. My question is, how do I convert each line from a string to an int?

I know i can do int(str) but how do I do this over each line of the file? I want to sum each number on each line and also count how many lines there are.

Ex of file contents:

> 5  
> 3  
> 5  
> 90
Brandon
  • 11
  • 4

2 Answers2

0
with open(filename) as f:
    content = f.readlines()
content = [int(x.strip()) for x in content] 

This reads every line in the file, converts the values into integers, and appends them all into a list called content.

To sum all the values just do:

sum = 0
for value in content:
    sum += content
Gavin Wong
  • 1,254
  • 1
  • 6
  • 15
0

You could answer this by googling, but try breaking this into steps:

Open the file:

with open("file.txt", 'r') as file:
    <do something with the file>

Read the lines out:

with open("file.txt", 'r') as file:
    lines = file.readlines()

Iterate through the lines:

with open("file.txt", 'r') as file:
    lines = file.readlines()
    for line in lines:
        <do something with the lines>

Add them up and print it out:

total = 0

with open("file.txt", 'r') as f:
    lines = f.readlines()
    for line in lines:
        total += int(line)

print("total is ", total)
Nathan Wride
  • 965
  • 1
  • 7
  • 28