On 09.03.2015 18:50, David Heiser wrote:


On 3/9/2015 9:50 AM, Alan Gauld wrote:
Somebody posted a question asking how to fond out if a file
exists. The message was in the queue and I thought I'd approved
it but it hasn't shown up yet. Sorry to the OP if I've messed up.

The answer is that you use the os.path.exists() function.
It takes a path as an argument which can be relative to
the cwd or absolute.

HTH

If you are testing for the existence of a file before opening it to read
it, you can use exception testing instead.

    try:
         data = open(filename, 'r').read()
    except NameError:
         do something else


But why are you watching out for a NameError ?
FileNotFoundError would be appropriate in Python3.3 and later.
In earlier versions you could rewrite this as (I think):

try:
    data_in = open(filename, 'r')
except IOError:
    do somthing
data = data_in.read()

to make sure you are detecting a problem with opening the file independently of one reading from it.

Wolfgang

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to