如何在 Jython 中使用 pickAFile() 创建错误消息?

How do I create an error message using pickAFile() in Jython?

我正在创建一个程序来对数字列表进行各种计算。

如果有人在使用 pickAFile() 选择文件时按 "Cancel",我该如何显示错误消息?目前,当我取消它时,我从 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

虽然 pickAFile() returns None 如果用户按下取消按钮,您可以引发一些异常:

fullPathName = pickAFile()
if not fullPathName:
    raise IOError('Cancel pressed')