我正在创建一个程序,对数字列表进行各种计算。
如果有人在选择pickAFile()
的文件时按“取消”,如何显示错误消息?目前,当我取消它时,我收到来自for line in file
行的错误消息。
错误消息是:
>"The error was:Stream closed
> I/O operation failed.
>
> I tried to read a file, and couldn't. Are you sure that file exists?
> If it does exist, did you specify the correct directory/folder?"
这是我的代码:
def selectFileCalculateStatistics():
fullPathName = pickAFile()
file = open(fullPathName, "r")
listNumbers = readListNumbers(file)
min = calculateMinimum(listNumbers)
max = calculateMaximum(listNumbers)
mean = calculateMean(listNumbers)
standardDeviation = calculateStandardDeviation(listNumbers, mean)
print("The minimum number for this list is: " + str(min))
print("The maximum number for this list is: \n" + str(max))
print("The mean number for this list is: " + str(round(mean, 2)))
print("The standard deviation for this list is: " + str(round(standardDeviation, 2)))
file.close()
def readListNumbers(fullPathName):
file = open(fullPathName, "r")
listNumbers = []
for line in file:
listNumbers.append(float(line.rstrip('\n')))
return listNumbers
答案 0 :(得分:0)
如果用户按下取消按钮,pickAFile()
会返回None
,您可以引发一些异常:
fullPathName = pickAFile()
if not fullPathName:
raise IOError('Cancel pressed')