2017-07-28 55 views
1

为我的编码分配我将创建一个文件,将读取一个csv文件,提供不同的属性做分析(由列值确定。我有这个代码工作完美,但后我加入我的第一次尝试/除块,我开始得到以下错误:尝试/除块导致ValueError

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是一个文件的链接与如果需要,你可以测试它,你可能已经猜到了,这是一个课堂作业,和我的工作无论如何,任何建议都不胜感激。


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) 

回答

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 
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 
+0

这工作完全解决我的错误;然而,这导致另一个问题。现在我的第二个try/expect子句在代码执行后继续循环,并要求用户选择一个属性。我尝试在我的else语句后添加break,这没有帮助。 –

+0

它保持循环,因为您使用'while True:'将其更改为变量,因此我们可以像'while isProcessing:'查看更新的答案那样将其切换为true或false – ewwink