Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a directory is on same partition

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)
like image 756
dbr Avatar asked Oct 30 '08 10:10

dbr


2 Answers

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
like image 144
CesarB Avatar answered Oct 18 '22 16:10

CesarB


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.
like image 36
Brian Avatar answered Oct 18 '22 15:10

Brian