[Tutor] try and file existence
Steven D'Aprano
steve at pearwood.info
Sat Aug 15 05:39:11 CEST 2015
On Fri, Aug 14, 2015 at 06:28:09PM -0700, Clayton Kirkwood wrote:
> try:
> fp = open( user_preferences )
> except( PermissionError ):
> else:
> with open(user_preferences ) as f:
try:
fp = open(user_preferences)
except (IOError, OSError) as e:
handle_error()
else:
with fp as f:
handle_file()
[...]
> what is the best way to find out if a file exists?
Try to open it and see what happens. If the open() succeeds, then the
file exists and can be read. If it fails, then either the file doesn't
exist, or it can't be read. Inspect the error to find out which.
There is also os.path.exists(filename), but you should avoid using that
if possible. The problem is this:
if os.path.exists(filename):
# file exists *right now*
# but a millisecond later, some other program deletes it...
# and now it doesn't exist any more
with open(filename) as f: # gives an error
...
This is called a "time of check to time of use" bug, and it is a major
cause of security bugs in software. Remember, even if you're the only
*person* using your computer, there could be hundreds of other programs
running in the background, and one of those might delete the file after
you've checked its existence.
Also, just because the file *exists* doesn't mean you can open it.
Perhaps the file is locked, unreadable, you don't have permissions, or
maybe even the disk is faulty and the file is corrupt and unreadable.
--
Steve
More information about the Tutor
mailing list