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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With