Adam Johnson
Adam Johnson

Reputation: 23

How to read file line by line in file?

I'm trying to learn python and I'm doing a problem out of a book but I'm stuck on one question. It asks me to read a file and each line contains an 'a' or a 's' and basically I have a total which is 500. If the line contains an 'a' it would add the amount next to it for example it would say "a 20" and it would add 20 to my total and for s it would subtract that amount. In the end I'm supposed to return the total after it made all the changes. So far I got

def NumFile(file:
    infile = open(file,'r')
    content = infile.readlines()
    infile.close()
    add = ('a','A')
    subtract = ('s','S')

after that I'm completely lost at how to start this

Upvotes: 2

Views: 535

Answers (2)

dermen
dermen

Reputation: 5362

A variation might be

f = open('myfile.txt','r')
lines  = f.readlines()
for i in lines:
  i = i.strip() # removes new line characters
  i = i.split() # splits a string by spaces and stores as a list
  key = i[0]    # an 'a' or an 's'
  val = int( i[1] )   # an integer, which you can now add to some other variable

Try adding print statements to see whats going on. The cool thing about python is you can stack multiple commands in a single line. Here is an equivalent code

for i in open('myfile.txt','r').readlines():
  i   = i.strip().split()
  key = i[0]
  val = int (i[1])

Upvotes: 0

NPE
NPE

Reputation: 500167

You need to iterate over the lines of the file. Here is a skeleton implementation:

# ...
with open(filename) as f:
    for line in f:
        tok = line.split()
        op = tok[0]
        qty = int(tok[1])
        # ...
# ...

This places every operation and quantity into op and qty respectively.

I leave it to you to fill in the blanks (# ...).

Upvotes: 5

Related Questions