简体   繁体   中英

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. I wanted to know, what if the file a.txt doesn't exist. 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. if you want to catch when the file does not exist you need to use the try.

If you want to output a message based on the type of error you can check the 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+ :

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

You can use os.path to verify the existence of a file path, for example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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