Try / Except Block导致ValueError

时间:2017-07-28 02:00:13

标签: python python-3.x csv dictionary try-except

我的编码分配我要创建一个文件,它将读取一个csv文件,提供不同的属性来进行分析(由列值决定。我有这个代码完美运行,但在我添加了我的第一次尝试/除外块我开始收到以下错误:

  

Traceback(最近一次调用最后一次):文件   " / Users / annerussell / Dropbox / Infotec 1040 / module 8 / csval.py",第49行,   在       row1 = next(读者,'结束')[0:] ValueError:关闭文件的I / O操作。

Here是指向您可以根据需要对其进行测试的文件的链接。你可能已经猜到这是一个课堂作业,我正在为gradschool学习python,所以任何建议都非常感谢。

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 个答案:

答案 0 :(得分:0)

简而言之:with块结束后,文件关闭。您无法从中读取,reader将失败。 可能你没有注意到with有一个空格缩进,用普通缩进替换它以便更清楚。

python context manager寻找更深入的理解。

这里的建议是将所有逻辑从try else块分解为process_file函数,并在with语句中调用它。

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

答案 1 :(得分:0)

使用with您需要将第二个条件移动到阻止或

替换

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

isProcessing = True
while isProcessing:
    ....
    infile = open(file_name, "rt")
    ...
    #end of line
    #print('Largest ',....
    infile.close()
    # end the loop
    isProcessing = False