Python Forum

Full Version: New here and I need help
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I need help with this code I can't get it to work
# Read the input file.. and store in tuples
with open("ALE.txt","r") as ins:

   # list to keep tuples
   array = []

   for line in ins:

       # while storing, calulate win percentage also
       tok = line.rstrip('\n').split(',')
       t = (tok[0], tok[1], tok[2],"{0:.3f}".format(float(tok[1])/(float(tok[1]) + float(tok[2]))))

       # add this to list
       array.append(t)

# sort the tuples, using 3rd column, win percentage
array = sorted(array, key=lambda x: x[3], reverse=True)

# open output file and write
output = open('output.txt', 'w')

for mytuple in array:
   output.write(",".join(mytuple) + "\n")

output.close()
Well, you are sorting by the percentage, but you stored the percentage as a string, not a float. Therefore it's probably sorting wrong. If you are having some other problem, it would be helpful if you told us what it was.
Sorry I'll get familiar with the posting rules

I get this error when I run the program

Error:
Traceback (most recent call last): File "/Users/luis/Desktop/Python /Project 3.py", line 7, in <module> for line in ins: ValueError: I/O operation on closed file.
Thanks for the help
I don't know why you would be getting that error. In terms of opening the file and looping through it, that code looks fine. You don't have it open in another application that could be blocking access, do you?