How to determine if a directory is on same partition
In C, you would use stat()
and compare the st_dev
field. In python, os.stat
should do the same.
import os
def same_partition(f1, f2):
return os.stat(f1).st_dev == os.stat(f2).st_dev
Another way is the “better to ask forgiveness than permission” approach—just try to rename it, and if that fails, catch the appropriate OSError
and try the copy approach. ie:
import errno
try:
os.rename(source, dest):
except IOError, ex:
if ex.errno == errno.EXDEV:
# perform the copy instead.
This has the advantage that it will also work on Windows, where st_dev is always 0 for all partitions.
Note that if you actually want to copy and then delete the source file (ie. perform a move), rather than just copy, then shutil.move will already do what you want:
Help on function move in module shutil: move(src, dst) Recursively move a file or directory to another location. If the destination is on our current filesystem, then simply use rename. Otherwise, copy src to the dst and then remove src.