views:

304

answers:

2

Say I have an input file, and a target directory. How do I determine if the input file is on the same hard-drive (or partition) as the target directory?

What I want to do is the copy a file if it's on a different, but move it if it's the same. For example:

target_directory = "/Volumes/externalDrive/something/"
input_foldername, input_filename = os.path.split(input_file)
if same_partition(input_foldername, target_directory):
    copy(input_file, target_directory)
else:
    move(input_file, target_directory)


Thanks to CesarB's answer, the same_partition function implemented:

import os
def same_partition(f1, f2):
    return os.stat(f1).st_dev == os.stat(f2).st_dev
+9  A: 

In C, you would use stat() and compare the st_dev field. In python, os.stat should do the same.

CesarB
Note that this won't work on windows though, which leaves st_dev as 0 for all drives. (Probably not an issue for the questioner since he specifies osX and linux tags)
Brian
+3  A: 

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.

[Edit] Updated due to Matthew Schinckel's comment to mention that shutil.move will delete the source after the copy, which isn't necessarily what is wanted, as the question just mentions copying.

Brian
Not quite exactly the same.The OP didn't seem to want the original deleted if they were on different disks.
Matthew Schinckel
Good point - I'd missed that.
Brian