1

for my coding assignment I am to create a file that will read a csv file, offer different attributes to do analysis over (determined by the column values. I had this code working perfectly, but after I added my first try/except block I started getting the following error:

Traceback (most recent call last): File "/Users/annerussell/Dropbox/Infotec 1040/module 8/csval.py", line 49, in row1=next(reader, 'end')[0:] ValueError: I/O operation on closed file.

Here is a link to a file you can test it with if desired. As you probably guessed this is a class assignment, and I am working on learning python for gradschool anyway so any suggestions are greatly appreciated.


import csv
print('Welcome to CSV Analytics!')

# Get file name and open the file
while True:
  try:
      file_name = input('Enter the name of the file you would like to process: ')
      with open(file_name, "rt") as infile:

# Select the attribute to be analyzed

        reader=csv.reader(infile)
        headers=next(reader)[0:]
        max=len(headers)
  except FileNotFoundError: 
      print('The file you entered could not be found. Please' \
           + ' enter a valid file name, ending in .csv.')
      continue

  except IOError:
      print('The file you selected could not be opened. Please ' \
            + 'enter a valid file name, ending in .csv.')
      continue
  except:
      print('There was an error opening or reading your file. Please ' \
            + 'enter a valid file name, ending in .csv.')
      continue
  else:


      print ('The attributes available to analyse are:')

      for col in range(1, max):
        print(col, headers[col])
      while True:
        try:
          choice=int(input('Please select the number of the attribute you would like to analyze '))
        except:
          print('Please enter the numeric value for the selection you choose.')
          continue
        else:
# Build a dictionary with the requested data
          dict1= {}
          numrows=-1
          row1=[]
          largest_value=0
          key_of_largest_value=0
          while row1 != 'end':
            row1=next(reader, 'end')[0:]
            if row1 !='end':
              numrows += 1
              key=row1[0]
              value=float(row1[choice])
              dict1[key] = value
              if value>largest_value:
                  largest_value=value
                  key_of_largest_value=key
          #    print('dictionary entry ( key, value)', key, value)
          print('Largest ', headers[choice], ' value is ', key_of_largest_value, ' with ', largest_value)  

2 Answers2

0

In short: After with block ends, file is closed. You can't read from it, reader will fail. Probably you didn't notice there is one-space indent for with, replace it with common indent so it will be more clear.

Seach for python context manager for more deep understanding.

Suggestion here is to factor out all logic from try else block to process_file function, and call it inside with statement.

with open(file_name, "rt") as infile:

    # Select the attribute to be analyzed

    reader=csv.reader(infile)
    headers=next(reader)[0:]
    max=len(headers)
    process_file(reader, headers, max)   # <-- like that
Ivan Klass
  • 6,407
  • 3
  • 30
  • 28
0

using with you need to move second condition to it block or

replace

with open(file_name, "rt") as infile:

with

isProcessing = True
while isProcessing:
    ....
    infile = open(file_name, "rt")
    ...
    #end of line
    #print('Largest ',....
    infile.close()
    # end the loop
    isProcessing = False
ewwink
  • 18,382
  • 2
  • 44
  • 54
  • This worked perfectly to solve my error; however, it lead to another issue. Now with my second try/expect clause it keeps looping back after the code executes and asking the user to select an attribute. I tried adding break after my else statement and this didn't help. – econ_gradstudent Jul 28 '17 at 03:22
  • it keep looping because you use `while True:` change it to variable so we can switch it true or false like `while isProcessing:` see updated answer – ewwink Jul 28 '17 at 03:46