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

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

.strip() is redundant with that form of .split()
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: 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.
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]) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.