How to tell if I can open a file or not

Donn Cave donn at u.washington.edu
Thu Jun 8 13:26:02 EDT 2000


Quoth Moshe Zadka <moshez at math.huji.ac.il>:
| On Thu, 8 Jun 2000, Skip Hollowell wrote:
|> 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.

One reason it's better than the C way:  sooner or later, you will check
whether a file can be opened, go ahead to open it on the strength of this
check, and find that it can't be opened anyway.  Your program crashes,
the air traffic control system goes out to lunch and hundreds die.

After you check, there's a period of time before you actually open
the file.  It's a brief window, but it's real, and many things can 
happen in that time if the system is busy, including changes to the
file's permission bits or even whether it exists.  Might as well
just open the file, and if it works then you have a green light.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list