how to determine if files are on same or different file systems

Peter Otten __peter__ at web.de
Sun Dec 7 05:35:17 EST 2003


Kamus of Kadizhar wrote:

> Thanks to everyone on this list.  I now have a functioning piece of
> python code!!  :-))
> 
> Now I'm trying to clean it up.
> 
> I have the same (or similar) lines repeated several times:
> 
>        shutil.copy2(newArrivalsDir+'/'+movie,archivesDir)
>        thumb = string.replace(movie,'.avi','.jpg')
>        shutil.copy2(newArrivalsDir+'/tn/'+thumb,archivesDir+'/tn/')
> 
> or
> 
>        os.rename(otherFavDir+'/'+movie,dir+'/'+movie)
>        thumb = string.replace(movie,'.avi','.jpg')
>        os.rename(otherFavDir+'/tn/'+thumb,dir+'/tn'+thumb)
> 
> what varies is the name of the function (shutil.copy2 or os.rename
> depending on if I am renaming or copying) and the names of the source
> and dest directories.  This particular snippet is repeated about a
> half-dozen times.

Probably time to turn it into a function 

def moveMovieAndThumb(fromDir, toDir, movieName):
    # your code

or similar.

> It would be nice if I could write a function that would determine if the
> source and destination are on the same file system or not, and thus use
> rename or copy appropriately, or if there is already such a built-in
> function.

No need to determine it beforehand, just try (untested):

def movefile(src, dst):
    try:
        os.rename(src, dst)
    except OSError:
        shutil.copy2(src, dst)
        os.remove(src)


Of course, if you are using Python 2.3 you should use shutil.move() as
pointed out by Serge Orlov; the above was mostly posted to illustrate the
popular concept "It's easier to ask forgiveness than permission", i. e.
with Python's powerful exception handling mechanism you need not fear the
failure of a particular code snippet, as long as you provide the
appropriate error handling.

Random remarks:
- You might take a look at os.path.join()
- Ok, this is paranoia, but I would ensure that ".avi" is only at the end of
the string
- Use methods of the str object rather than functions in the string module,
e. g. "abc".replace("a", "d") rather than string.replace("abc", "a", "d")

Peter




More information about the Python-list mailing list