2

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

bereal
  • 32,519
  • 6
  • 58
  • 104

2 Answers2

5

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

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 2
    `.strip()` is redundant with that form of `.split()` – Jon Clements Apr 08 '13 at 06:53
  • Great answer, just wondering why you left some parts out? Was it so OP can learn by himself? Sometimes I think it's best to just show it all since most text books are old and don't teach good practices unlike this site – jamylak Apr 08 '13 at 07:17
  • @jamylak: That's exactly my thinking. I decided to show the parts where I felt the self-learner would struggle to write clear, correct and idiomatically up-to-date code. At the same time, I felt it would be a good exercise to let them write the simpler (but at the same time more important) parts of the logic. – NPE Apr 08 '13 at 07:21
0

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])
dermen
  • 5,252
  • 4
  • 23
  • 34