【问题标题】:How to open file using try except in python? [closed]如何在python中使用try打开文件? [关闭]
【发布时间】:2013-11-25 03:50:55
【问题描述】:

我有一个 txt 文件,我想在名为 animallog1.txt 的程序中使用。我如何打开它,以便可以使用 try 和 except 在我的程序中使用它。我知道如何使用 open 函数使用文件,但不使用 try except。有人能告诉我它是怎么做的吗

【问题讨论】:

  • 1.目前尚不清楚您要问什么,但这里是您可能的答案:stackoverflow.com/questions/8380006/… 2. 在提出此类问题之前,请尝试至少投入最少的研究工作。 try-except 子句是标准的 python 组合,如果您打开文档,您会发现无法使用 try 和 except...打开文件...
  • 您无法使用try...except 打开文件。我认为要求的是像往常一样打开文件,并在使用try...except 时捕获异常。
  • 也许这就是你想要的? diveintopython.net/file_handling

标签: python


【解决方案1】:

你说的很模糊,但我会试着回答你的问题。使用try 和except 的原因是为了捕获错误。在打开文件时,您会得到一个IOError。所以这就是你打开文件的方式:

try:
    with open("file.txt","r") as f:
        #stuff goes here
except IOError:
    #do what you want if there is an error with the file opening

【讨论】:

    【解决方案2】:

    尝试例外不是做某事的方法。这是一种处理错误的方法。查看this page 了解更多信息。基本上,如果你认为你会得到一个错误,你把你认为会产生错误的代码放在try 中。然后,在except 中放置错误发生时要执行的代码。

    例如:

    try:
        a = int("apple")
    except ValueError:
        a = "apple"
    

    这里发生的是,在 try 语句中,该行产生了一个ValueError。它被包含在 except 子句中,而是计算那里的行。

    所以,我给你的建议是:

    try:
        f = open("test.txt", "r")
    except IOError:    #This means that the file does not exist (or some other IOError)
        print "Oops, no file by that name"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-14
      • 2020-01-14
      • 2013-07-01
      • 2023-04-03
      • 1970-01-01
      • 2012-02-05
      • 1970-01-01
      相关资源
      最近更新 更多