How does Python handle probing to see if a file already exists?
Greg Ewing
see_reply_address at something.invalid
Tue Nov 5 19:55:45 EST 2002
Gerhard Häring wrote:
> It's also possible to check if a file exists before trying to open it:
>
> if os.path.exists("/usr/bin/foo"):
> # more code here
>
> But the existence of the file does not guarantee you have the necessary
> permissions to actually open it. It could also be deleted in the millisecond or
> so between your check and trying to open it.
The problem in Christopher's case is actually the other
way around -- a file could be *created* in between probing
and opening a new file.
This presents a slight problem. What we really need to do
is attempt to open the new file with a mode which says
"create the file, or fail if it already exists" -- but
there doesn't seem to be any such mode.
On Unix, it can be done using lower-level calls:
from os import open, fdopen, O_CREAT, O_EXCL
try:
fd = open(new_file_name, O_CREAT | O_EXCL, 0666)
f = fdopen(fd, "w")
except IOError:
...
--
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
More information about the Python-list
mailing list