How does Python handle probing to see if a file already exists?

Lemniscate d_blade8 at hotmail.com
Tue Nov 5 18:03:41 EST 2002


Hi.  Before I start, I posted this sep. but wanted to put it here to. 
Gustavo put some nice work together However, the os.path module has a
ton of tools that you may want to get familiar with currently.  Plus,
there could be "issues" depending on your code.  You need to check if
it is writable AND whether it is a file (not just whether the "path"
exists).  For example, running a directory under G.'s code:

> if os.access("some-filename", os.W_OK):
>    # neat, I can write to the file.
>    ...

will attempt to let you write to a directory like it is a file.  For
example, "Book Source" is a directory on my computer:

>>> os.access('Books Source', os.W_OK)
1
>>> # It's writable, let's try to write to it like a file
>>> file("Books Source", 'w').write("Nothing doing, here's an
error...")
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
IOError: [Errno 13] Permission denied: 'Books Source'
>>> # so, W_OK is yes, but you can't write to it

So, you see, you *may* need to do some checking.  Maybe as so...

>>> import os
>>> import os.path
>>> Possible_name = "Books Source"
>>> os.access(Possible_name, os.W_OK) and
os.path.isfile(Possible_name)
0
>>> os.access(Possible_name, os.W_OK) and os.path.isdir(Possible_name)
1
>>> # ahh, it's a dir, not a file

Just a couple of ideas so that you don't get stuck.

Chris
"Christopher R. Culver" <Kricxjo.neniuspamajxo at yahoo.com> wrote in message news:<pan.2002.11.05.10.28.55.506357 at yahoo.com>...
> Hello all,
> 
> I've just begun learning Python after already getting pretty proficient in
> C. However, I'm having a problem with a simple copying program. Ideally,
> the program would check to see if the destination already exists and
> prompt the user. In this this would be as easy as saying:
> 
> probe_destination = fopen(/usr/bin/foo, 'r')
> if (probe_destination)
> {
> some code here;
> }
> 
> However, translating that directly into Python doesn't work because if
> Python can't find a file to open, it doesn't just return 0, it gives an
> error and exits. How can I write this functionality in Python so that it
> returns 0 and continues, or does Python have a totally different way of
> handling this problem than C?
> 
> Christopher Culver



More information about the Python-list mailing list