【问题标题】:How do I create an error message using pickAFile() in Jython?如何在 Jython 中使用 pickAFile() 创建错误消息?
【发布时间】:2015-03-21 07:37:30
【问题描述】:

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

如果有人在选择带有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

【问题讨论】:

  • readListNumbers() 中,尝试选择与file 不同的变量名称。覆盖内置函数可能会产生奇怪的副作用。
  • 注意,谢谢。不过,有什么提示可以提供错误消息吗?
  • 我不了解 Jython,所以我从未使用过 pickAFile() 函数。也许看看如果用户选择“取消”它会返回什么,并与之进行比较?例如如果返回 None,则添加一行 if fullPathName is None: [error msg] else: [do some work]
  • 不幸的是,这不是错误消息,否则我就是这样做的。 “错误是:流关闭 I/O 操作失败。我尝试读取文件,但无法读取。您确定该文件存在吗?如果存在,您是否指定了正确的目录/文件夹?”
  • 嗯,那我没主意了。但是您应该在问题中添加该错误消息 - 它会让其他人更容易帮助您。

标签: list file numbers message jython


【解决方案1】:

虽然pickAFile() 返回None,但如果用户按下取消按钮,您可能会引发一些异常:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 2021-07-04
    • 2021-05-03
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    相关资源
    最近更新 更多