简体   繁体   English

在try-except内部使用运算符

[英]with operator inside try-except

I have the following code: 我有以下代码:

with open("a.txt") as f:
    data = f.read()
    # operation on data

This will close the file a.txt if there is any Error on my operations on data. 如果我对数据的操作出现任何错误,将关闭文件a.txt I wanted to know, what if the file a.txt doesn't exist. 我想知道,如果文件a.txt不存在怎么办。 Should my code be: 我的代码应该是:

try:
    with open("a.txt") as f:
        data = f.read()
        # operation on data
except IOError:
    print "No such File"

If the file does not exist unless you use the try/except an error will be raised, if the file does not exist nothing will be opened so there will be nothing to close. 如果该文件不存在,除非您使用try/except ,否则将引发错误;如果该文件不存在,则不会打开任何内容,因此不会关闭任何内容。 if you want to catch when the file does not exist you need to use the try. 如果要在文件不存在时捕获,则需要使用try。

If you want to output a message based on the type of error you can check the errno: 如果要根据错误类型输出消息,则可以检查errno:

try:
    with open("a.txt") as f:
       data = f.read()
except IOError as e:
    if e.errno == 2:
        print("No such File")

If you want to create the file if it does not exist or else read from it you can use a+ : 如果要创建文件(如果文件不存在或从文件中读取),则可以使用a+

with open("a.txt","a+") as f:

You can use os.path to verify the existence of a file path, for example: 您可以使用os.path来验证文件路径的存在,例如:

if os.path.exists('data.txt'):
    with open('data.txt', 'r') as data:
        # do stuff with file here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM