1

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"
KKa
  • 408
  • 4
  • 19

2 Answers2

0

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:
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
0

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
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
  • EAFP vs LBYL, isn't it more pythonic to EAFP: http://stackoverflow.com/questions/6092992/why-is-it-easier-to-ask-forgiveness-than-permission-in-python-but-not-in-java. You still may have a race condition where is does exist for the if but not the open... – AChampion Apr 11 '15 at 13:54