【问题标题】:Lists, Tuples, and Statistics Program Try-Except Block Error列表、元组和统计程序 Try-Except Block Error
【发布时间】:2015-03-16 03:56:08
【问题描述】:

我正在为我的入门课程编写列表、元组和统计程序,并且在使用 try-except 块时遇到了一些困难。我们应该制作的程序应该要求用户命名要输入的文件,然后提供有关该文件中数字的一些信息。我的所有信息显示都正常工作,但无法编写 try-except 块。程序只需要接受文件名“new_numbers.txt”而不接受其他任何内容。

这是我的代码的顶部:

    def main():
        #Get the name of the file from the user
        while(True):
                try:
                    input("Enter the name of the file you would like to open: ")
                except ValueError:
                    print("That file does not exist. Please enter a valid file.")
                    break

【问题讨论】:

  • 在你的 try 语句中,没有什么可以让它失败的。
  • 是的,这就是我一直遇到的问题。这是我们完成的第一个输入不是数字的程序,所以我不知道如何设置它
  • 有回溯吗?
  • 不,现在只是循环播放。

标签: python list error-handling tuples try-except


【解决方案1】:

您需要分配来自input 的值,并尝试open 以查看相关文件是否在...:

def main():
    #Get the name of the file from the user
    while(True):
        try:
            fn = input('Enter the name of the file you would like to open: ')
            f = open(fn)
        except IOError:
            print('File {} does not exist. Please enter a valid file.'.format(fn))
        else:
            break

另外请注意,只有在出现no more错误时,您才应该break;在这种情况下,打开的文件对象已准备好作为变量f

【讨论】:

  • 非常感谢!这让我困惑了很长一段时间。
  • @jnfp7c,不客气!请记住(在您提出问题后已经过了足够的时间)接受答案(单击其左侧的复选标记形状的轮廓),这是 StackOverflow 礼仪的关键部分!-(
猜你喜欢
  • 1970-01-01
  • 2015-10-24
  • 2021-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多