How to determine if a directory is in a single partition

Say I have an input file and a destination directory. How to determine if the input file is the same hard disk (or partition) as the destination directory?

What I want to do is copy the file if it is different from the other, but move it if it is 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 is same_partition :

 import os def same_partition(f1, f2): return os.stat(f1).st_dev == os.stat(f2).st_dev 
+6
python linux filesystems macos
source share
2 answers

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

+11
source share

Another way is the β€œit's better to ask forgiveness than permission" approach, just try renaming it, and if that fails, catch the appropriate OSError and try using the copy method. i.e:

 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.

Please note: if you really want to copy and then delete the source file (i.e., perform the transition), and not 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 a comment by Matthew Shinkel, to mention that shutil.move will delete the source code after the copy, which is not necessarily what you need, as the question just mentions copying.

+3
source share

All Articles