为我的编码分配我将创建一个文件,将读取一个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)
这工作完全解决我的错误;然而,这导致另一个问题。现在我的第二个try/expect子句在代码执行后继续循环,并要求用户选择一个属性。我尝试在我的else语句后添加break,这没有帮助。 –
它保持循环,因为您使用'while True:'将其更改为变量,因此我们可以像'while isProcessing:'查看更新的答案那样将其切换为true或false – ewwink