Verified Input.
Rikard Bosnjakovic
rikard at strakt.com
Thu Oct 18 00:34:32 EDT 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.
--
Cheers,
------------------------------------------------------------------------
Rikard Bosnjakovic http://bos.hack.org/cv/
Python Hacker rikard at strakt.com
AB Strakt bos at hack.org
More information about the Python-list
mailing list