How to tell if I can open a file or not

andres at corrada.com andres at corrada.com
Thu Jun 8 10:42:54 EDT 2000


On Thu, Jun 08, 2000 at 08:51:36AM -0400, 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().
> 
> 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.
> 

Since python is bombing that means you have raised an IOError exception with
your open() statement. Try the "try" statement!

try:
    f = open('/path/to/file')
    .
    .
    .
except IOError:
    # We probably can't open this file for reading
    continue
    
Of course, there are many reasons why open may fail so this does not
guarantee that you are trapping only the files you cannot read.

------------------------------------------------------
Andres Corrada-Emmanuel   Email: andres at corrada.com
------------------------------------------------------




More information about the Python-list mailing list