0

Using functions, how would I print the lowest, highest, and average of my PAY list that I read from a file?

try: text_file = open ("Pay.txt", "w") text_file.writelines(Pay) text_file.close() except (IOError): print 'Error opening/writing Pay.txt' try: text_file= open("Pay.txt","r") PAY_= text_file.readlines() text_file.close() PAY_.sort() 

I've never set up anything like this, could anyone get me started?I'll thank you ahead of time for your replies. Keep in mind I'm new here, I don't know exactly how you do things...bear with me please.

1 Answer 1

2

Presuming that you have one number per line:

numbers = [float(line) for line in open('Pay.txt') if line.strip()] if numbers: print 'min', min(numbers) print 'max', max(numbers) print 'avg', sum(numbers) / len(numbers) else: print 'file is empty or all lines are blank' 
Sign up to request clarification or add additional context in comments.

5 Comments

@ John Machin Thanks, And this structure would go right under my read file that I have posted?
@user735324: It's not a "structure", and it replaces the read code which you posted (which does nothing useful except closing the file). By the way, if all you are going to do with try/except is replace precise error messages with 'error opening/writing ..' or suchlike, then don't bother.
code has a structure to it, does it not? I appreciate your help John, wish I could give you some points.
hmmmmm....It's giving me this error: numbers = IOError: [Errno 2] No such file or directory: 'Pay.txt' ---not sure why, I wrote the file?
@user735324: If you are writing it in the same script, check for name typo. Otherwise: Maybe it was deleted after you wrote it. Maybe it's in a directory other than your current working directory.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.