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)


Asked by: Haris614 | Posted: 24-09-2021






Answer 1

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

Answered by: Melissa738 | Posted: 25-10-2021



Answer 2

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.

Answered by: Sienna479 | Posted: 25-10-2021



Similar questions

python - Determine if directory is under git control

How can I tell if a given directory is part of a git respository? (The following is in python, but bash or something would be fine.) os.path.isdir('.svn') will tell you if the current directory is controlled by Subversion. Mercurial and Git just have a .hg/.git at the top of the repository, so for hg I can use os.system('hg -q stat 2> /dev/null > ...


python - Determine whether any files have been added, removed, or modified in a directory

I'm trying to write a Python script that will get the md5sum of all files in a directory (in Linux). Which I believe I have done in the code below. I want to be able to run this to make sure no files within the directory have changed, and no files have been added for deleted. The problem is if I make a change to a file in the directory but then change it back. I get a different result from running the f...


path - Determine a JDK install directory through Python

I'm currently writing a program in Python, and I would like to determine the path to the JDK install directory if it's on the system. Is there a way of doing this in Python? If not, is there a way of doing it in Java (or another language)? If it is the latter, I could open a subprocess from within Python to obtain it. Thanks.


python - Determine the scrapy root directory

I'd like to be able to read a file relative to the scrapy root directory, as described in the documentation. Is there a way of determining this path from inside the spider?


awk - Determine total size of SVN directory and store in python variable

this prints the directory size, but how can i save the output to a python variable, instead of print. svn list -vR http://myIP/repos/test | awk '{sum+=$3; i++} END {print sum/1024000}' but i need to store this print in a python variable; proc = subprocess.Popen(svnproc, stdout=subprocess.PIPE, shell=True) output = proc.stdout.read() Print str(output) nast...


python - How do you properly determine the current script directory?

I would like to see what is the best way to determine the current script directory in Python. I discovered that, due to the many ways of calling Python code, it is hard to find a good solution. Here are some problems: __file__ is not defined if the script is executed with exec, execfile __module__ is defined only in modules


How do you determine the current Python egg cache directory?

I'm aware that you can override the egg cache directory with the environment variable PYTHON_EGG_CACHE, and that you can look that override up in os.envrion. It looks like the default for Python 2.7 on Ubuntu 16 is /.cache/Python-Eggs. How would you log the location of the egg cache when there is no PYTHON_EGG_CACHE provided in the environment?


python - Determine a file's path(s) relative to a directory, including symlinks

I have a directory with thousands of descendants (at least 1,000, probably no more than 20,000). Given a file path (which is guaranteed to exist), I want to know where that file can be found inside that directory -- including via symlinks. For example, given: The directory path is /base. The real file path is /elsewhere/myfile. /base is a symlin...


Is there a Python function to determine the root directory with os module?

I recently started learning Python language and the textbook I have, while presenting the os module, explained how to use the os.name attribute in order to determine the root directory of the operative system - so, a hardcoded solution based on the if-elif-else construct. Just for the sake of practising and start to get keen on this language, I tried to generalise this solution.


python - OS X: Determine Trash location for a given path

Simply moving the file to ~/.Trash/ will not work, as if the file os on an external drive, it will move the file to the main system drive.. Also, there are other conditions, like files on external drives get moved to /Volumes/.Trash/501/ (or whatever the current user's ID is) Given a file or folder path, what is the correct way to determine the trash folder? I imagine the language ...


python - How can you determine a point is between two other points on a line segment?

Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point. How can you determine if another point c is on the line segment defined by a and b? I use python most, but examples in any language would be helpful.


python - How do I determine if an email is Base64 encoded?

I am having difficulty determining if the body of a text email message is base64 encoded. if it is then use this line of code; making use of jython 2.2.1 dirty=base64.decodebytes(dirty) else continue as normal. This is the code I have atm. What line of code will allow me to extract this from the email: "Content-Transfer-Encoding: base64" import email, ...


python - How do I determine all of my IP addresses when I have multiple NICs?

I have multiple Network Interface Cards on my computer, each with its own IP address. When I use gethostbyname(gethostname()) from Python's (built-in) socket module, it will only return one of them. How do I get the others?


macos - How to determine number of files on a drive with Python?

I have been trying to figure out how to retrieve (quickly) the number of files on a given HFS+ drive with python. I have been playing with os.statvfs and such, but can't quite get anything (that seems helpful to me). Any ideas? Edit: Let me be a bit more specific. =] I am writing a timemachine-like wrapper around rsync for various reasons, and would like a very fast estimate...


Determine if a function is available in a Python module

I am working on some Python socket code that's using the socket.fromfd() function. However, this method is not available on all platforms, so I am writing some fallback code in the case that the method is not defined. What's the best way to determine if a method is defined at runtime? Is the...


How do I determine if an object has an attribute in Python?

How do I determine if an object has some attribute? For example: >>> a = SomeClass() >>> a.property Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: SomeClass instance has no attribute 'property' How do I tell if a has the attribute property before using it?


code analysis - Tool to determine what lowest version of Python required?

Is there something similar to Pylint, that will look at a Python script (or run it), and determine which version of Python each line (or function) requires? For example, theoretical usage: $ magic_tool <EOF with something: pass EOF 1: 'with' statement requires Python 2.6 or greater $ magic_tool <EOF class Something: @classmethod def blah(cls): pass EOF 2: classmethod requi...


python - How can I determine the monitor refresh rate?

Is there a cross platform way to get the monitor's refresh rate in python (2.6)? I'm using Pygame and PyOpenGL, if that helps. I don't need to change the refresh rate, I just need to know what it is.


How to determine whether java is installed on a system through python?

Using Python, I want to know whether Java is installed.






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top