How to tell if I can open a file or not

Moshe Zadka moshez at math.huji.ac.il
Thu Jun 8 12:39:20 EDT 2000


On Thu, 8 Jun 2000, Skip Hollowell wrote:

> I have a indexer that I am writing that goest through a user-specified
> directory and all subdirectories and indexes all the .htm* file contained
> therein.  This works great until I get to a file that someone has chmod-ed
> so that I can't read it.  Then I bomb after the open().

Let's be exact: you get an exception when open() fails. This is a Good
Thing(TM): you won't be able to forget to check if open() fails. The
downside, of course, is that you have to handle the exception. I suggest
that in your main loop, just put a try/except for IOError and os.error. If
all this exception handling stuff went over your head, sit down and read
the fine Python tutorial -- it covers exceptions quite nicely.

> Is there a way I can check the attrbutes of the file before I open it?  This
> is easy enough in c or perl, but have yet to find an equivalent in Python.

Try os.stat and the stat module, though exception handling is probably
better.

--
Moshe Zadka <moshez at math.huji.ac.il>
http://www.oreilly.com/news/prescod_0300.html
http://www.linux.org.il -- we put the penguin in .com





More information about the Python-list mailing list