jeabesli
jeabesli

Reputation: 83

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?

Upvotes: 3

Views: 25408

Answers (3)

Vishal Yarabandi
Vishal Yarabandi

Reputation: 457

It works for me. Why can't you make use of os.path.exists()

for x in l:
    if not os.path.exists(x):
        print >> sys.stderr , "No such file", x

Upvotes: 0

jesseops
jesseops

Reputation: 406

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.

Upvotes: 4

SnakeFoot
SnakeFoot

Reputation: 174

You have the os.path.exists function:

import os.path
os.path.exists(file_path)

returns bool

Upvotes: 1

Related Questions