Newbie Help

Jeff Epler jepler at unpythonic.net
Sun Sep 21 04:46:08 CEST 2003


On Sat, Sep 20, 2003 at 10:16:58AM -0400, jimbob wrote:
> Hello all,
> I am trying to move a file from one dir to another. However I keep
> receiving this error:
> 
> 
> OSError: [Errno 18] Invalid cross-device link
>  
> 
> which stemms from the code:
> 
> 
> os.rename('/home/me/%s' %z ,'/home1/pics/%s' % z)
> 
> /home1/pics is on a different dirve(hdb1) as opposed to /home which is on
> (hda1). Any ideas as to how to get around this?

It means just what it says.  os.rename() is a wrapper around the
unix rename() syscall, which fails when the files are on different
partitions.  rename() must be "atomic", but moving a file to a different
filesystem requires that the contents of the old file be read and then
written to the new file, with the original file deleted after the
write is complete. (Or, unlink the new and return an error if the copy
could not be completed)

If os.rename gives EXDEV, then you'll have to use another method.
shutil.copy() + os.unlink should do the trick.  Something like the
following (untested, so don't blame me when it unlinks the original file
without creating the new one):
    def rename(old, new):
        try:
            os.rename(old, new)
        except os.error, detail:
            if detail.errno == errno.EXDEV:
                try:
                    shutil.copy(old, new)
                except:
                    os.unlink(new)
                    raise
                os.unlink(old)
            # if desired, deal with other errors
            else: 
                raise

Jeff





More information about the Python-list mailing list