【问题标题】:Cannot stop program from crashing with wrong file entered by user无法阻止程序因用户输入的错误文件而崩溃
【发布时间】:2016-11-18 15:54:56
【问题描述】:

我正在创建一个程序,它要求用户选择要在程序中运行的文件,但是当输入不存在的文件名时,我无法阻止程序崩溃。我尝试过 try 语句和 for 循环,但它们都给出了错误。我选择文件的代码如下:

data = []
print "Welcome to the program!"
chosen = raw_input("Please choose a file name to use with the program:")
for line in open(chosen):
    our_data = line.split(",")

    data.append(our_data)

【问题讨论】:

  • 请说明您是如何尝试try 语句的。这是正确的做法。
  • try 是正确的解决方案。向我们展示您使用它的代码。

标签: python loops for-loop try-catch raw-input


【解决方案1】:

添加例外:

data = []
print "Welcome to the program!"
chosen = raw_input("Please choose a file name to use with the program:")
try:
  for line in open(chosen):
      our_data = line.split(",")

      data.append(our_data)
except IOError:
      print('File does not exist!')

【讨论】:

    【解决方案2】:

    在不使用异常的情况下,您可以简单地检查文件是否存在,如果不再请求。

    import os.path 
    
    data = []
    print "Welcome to the program!"
    chosen='not-a-file'
    while not os.path.isfile(chosen):
        if chosen != 'not-a-file':
            print("File does not exist!")
        chosen = raw_input("Please choose a file name to use with the program:")
    for line in open(chosen):
        our_data = line.split(",")
    
        data.append(our_data)
    

    【讨论】:

      【解决方案3】:

      RTM

      import sys
      
      try:
          f = open('myfile.txt')
          s = f.readline()
          i = int(s.strip())
      except IOError as e:
          print "I/O error({0}): {1}".format(e.errno, e.strerror)
      except ValueError:
          print "Could not convert data to an integer."
      except:
          print "Unexpected error:", sys.exc_info()[0]
          raise
      

      【讨论】:

        猜你喜欢
        • 2013-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-22
        • 1970-01-01
        • 2015-11-14
        • 1970-01-01
        相关资源
        最近更新 更多