Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python file does not exist exception

I am trying to open a file and read from it and if the file is not there, I catch the exception and throw an error to stderr. The code that I have:

for x in l:
    try:        
        f = open(x,'r')
    except IOError:
        print >> sys.stderr, "No such file" , x

but nothing is being printed to stderr, does open create a new file if the file name doesn't exist or is the problem somewhere else?

like image 551
jeabesli Avatar asked Dec 11 '25 03:12

jeabesli


1 Answers

Try this:

from __future__ import print_statement
import sys

if os.path.exists(x):
    with open(x, 'r') as f:
        # Do Stuff with file
else:
    print("No such file '{}'".format(x), file=sys.stderr)

The goal here is to be as clear as possible about what is happening. We first check if the file exists by calling os.path.exists(x). This returns True or False, allowing us to simply use it in an if statement.

From there you can open the file for reading, or handle exiting as you like. Using the Python3 style print function allows you to explicitly declare where your output goes, in this case to stderr.

like image 190
jesseops Avatar answered Dec 13 '25 16:12

jesseops



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!