[Tutor] Copy without overwrite?

Lloyd Hugh Allen chandrakirti at gmail.com
Tue Sep 21 12:53:05 CEST 2004

I don't know whether this would be considered to be cheating (thePath
is a string containing the relevant path; theFile was created by
opening and reading the old file):

def notOverwrite(thePath, theFile):
        attempt = open(thePath)   #default argument for mode is 'r', read
        attempt.close()    #we successfully opened thePath. It exists.
Leave it alone.
    except IOError:
        newFile = open(thePath, 'w')    
                                     #if we're here, then we weren't
allowed to read the old file
                                     #PROBABLYbecause it wasn't there.
It would be worth
                                     #putting this in another try in
case the file is protected or exists
                                     #but we don't have read/write
permission; I'm not sure how to tell
                                     #(easily) whether it exists if we
don't have read, unless we have
                                     #read access to the directory in
order to manually check the dir.
        data = theFile.read()

also ensure that you close theFile. The try/except is very, very
powerful; but like I tried to say in the comment, try to be aware of
all the cases in which your statement will raise that particular
exception. And don't use else, unless you enjoy spending lots of time
guessing why your program is doing unpredictable (and wrong) things.

I thougt that I wrote something about being totally hosed as far as
applying this function within a path for which you have access
permission and write permission but not read permission (a drop box),
but I don't see that explicitly looking back through my message. I
would only feel comfortable applying this if you have "7" permission
(read/write/access) to the directory and "6" (read/write) permission
to the file.

On Tue, 21 Sep 2004 11:59:29 +0200, Bernard Lebel
<python at bernardlebel.com> wrote:
> Hello,
> Is there a simple way to copy files and directory without any overwriting if the destination tree
> structure contains files and directory of the same name? Basically that would just add new elements
> to the destination structure, and leave the existing structure intact.
> Thanks
> Bernard
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

More information about the Tutor mailing list