Python (2.7) Operation on a closed file error -


another user here helped me refine code below. have sorted list of integers, don't know how original list since statement closes file reading from. have returned variable "list" , have print statement it, if can find way produce it. thought easy enough use readlines fuction, can't figure out how that. help! still new python...

import random open("1000.txt", "w") f:     x in range(1000):         f.write(str(random.randint(0, 9999))+"\n")  def readlist():     infile = raw_input("input file name: ")     rawlist = list()         open(infile, 'r') infi:         line in infi:             rawlist.append(int(line))     sortedlist = sortlist(rawlist) #function call sorting list, returned sorted list stored     n = int(raw_input("which number want return?: "))     user_num = int(float(n-1))     return sortedlist, user_num, list  def sortlist(inplist): #function needs list input , returns sorted list     inplist.sort()      return inplist  if __name__=='__main__': #this how main defined in python     sortedlist, list, user_num = readlist() #function call of readlist, returned 2 objects stored in variables     first = sortedlist[0]      lines = len(sortedlist)     orig_min_val = min(list)     orig_max_val = max(list)     minimum_val = min(sortedlist)     maximum_val = max(sortedlist)     if user_num > 1000:         print user_num, "is greater 1000!" # don't need brackets when printing     elif user_num > lines:         print "there aren't many numbers in list!"     elif lines < 1000:         print "warning: only", lines, "numbers read list!"     print "before sort:"     print "min is", orig_min_val     print "max is", orig_max_val     print "after sort:"     print "min is", minimum_val     print "max is", maximum_val     print user_num 

spelling , ordering important in programming. have couple small blunders.

first, line:

return sortedlist, user_num, list 

is returning called list. however, don't have variable called list anywhere in method; you're returning reference python class list (notice how syntax highlighting in post colors blue? that's why). want instead return rawlist this:

return sortedlist, user_num, rawlist 

second, line:

sortedlist, list, user_num = readlist() 

is getting results return. if closely, you'll see they're in wrong order. not that, assigning 1 of values python class list! bad. recommend rename variable in __main__ method list rawlist, , make sure variables correctly ordered so:

sortedlist, user_num, rawlist = readlist() 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -