除了在python中,如何使用try打开文件?

rgg*_*god 3 python

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

Rya*_*axe 9

你说的很模糊,但我会试着回答你的问题。您使用tryand的原因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
Run Code Online (Sandbox Code Playgroud)


小智 1

Try except 不是一种做某事的方法。这是一种处理错误的方法。查看此页面了解更多信息。基本上,如果您认为会出现错误,则可以将您认为会产生错误的代码放入try. 然后,您将在错误确实发生时想要执行的代码放入except.

例如:

try:
    a = int("apple")
except ValueError:
    a = "apple"
Run Code Online (Sandbox Code Playgroud)

这里发生的是,在 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"
Run Code Online (Sandbox Code Playgroud)