[Tutor] file exists question

David Heiser davidheiserca at gmail.com
Mon Mar 9 18:50:06 CET 2015



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





More information about the Tutor mailing list