[Tutor] checking if file exists

Marabe, Nelsie N.Marabe at spitech.com
Thu Oct 14 18:08:42 CEST 2004

Another solution is to use the os module.

import os

if os.path.exists(file):
	print "file exists"
	print "file not exists"

-----Original Message-----
From: Tim Wilson [mailto:wilson at visi.com] 
Sent: Thursday, October 14, 2004 11:52 PM
To: Mark Kels; tutor at python.org
Subject: Re: [Tutor] checking if file exists

On 10/14/04 10:43 AM, "Mark Kels" <Mark.Kels at gmail.com> wrote:

> How can I check if file exists in a folder ?
> I tryed to do it with an if statment, but I cant use the error as a 
> boolean expression... Any suggestions ?

I'm sure someone will suggest something most specific, but this is where
the try-except combination comes in. It would look something like this:

    f = open(filename)
    etc etc etc
except IOError:
    print "There's no %s file there." % filename
    etc etc etc


Tim Wilson
Twin Cities, Minnesota, USA
Educational technology guy, Linux and OS X fan, Grad. student, Daddy
mailto: wilson at visi.com   aim: tis270   public key: 0x8C0F8813

More information about the Tutor mailing list