Verified Input.

Rikard Bosnjakovic rikard at
Thu Oct 18 06:34:32 CEST 2001

Alec D. Cheah wrote:

> How do verified from input the variable entered is a file or a path
> and how do you check whether it exist or not??
> Help...
> Newbie on Python....

 >>> import os
 >>> s = "/tmp/foobar"
 >>> os.stat(s)
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
OSError: [Errno 2] No such file or directory: '/tmp/foobar'
 >>> open(s, "w")
<open file '/tmp/foobar', mode 'w' at 0x80f39e0>
 >>> from stat import *
 >>> mode = os.stat(s)[ST_MODE]
 >>> if S_ISDIR(mode):
...   print "dir"
... elif S_ISREG(mode):
...   print "regular file"
... else:
...   print "something else"
regular file

I.e., you should enclose the stat() within a try-except in case the file 
does not exist.

Rikard Bosnjakovic                     
Python Hacker                                          rikard at
AB Strakt                                                   bos at

More information about the Python-list mailing list