I have a bunch of file paths, such as:
path1 = "./base/folder1/subfolder"
path2 = "./base/folder2/"
I am trying to write a function that can give me the relative difference between the paths. Using the paths above:
>>> get_path_difference(path1, path2)
"../../folder2"
>>> get_path_difference(path2, path1)
"../folder1/subfolder"
I've had a look through the os.path
module, since it seems like this should be a common thing, but either I don't know the terminology or it isn't there.
path. samefile() method in Python is used to check whether the given two pathnames refer to the same file or directory or not. This is determined by comparing device number and i-node number of the given paths.
In order to obtain the Current Working Directory in Python, use the os. getcwd() method. This function of the Python OS module returns the string containing the absolute path to the current working directory.
relpath() method in Python is used to get a relative filepath to the given path either from the current working directory or from the given directory. Note: This method only computes the relative path. The existence of the given path or directory is not checked.
path. isabs() method in Python is used to check whether the specified path is an absolute path or not. On Unix platforms, an absolute path begins with a forward slash ('/') and on Windows it begins with a backward slash ('\') after removing any potential drive letter.
path1: A path-like object representing the first file system path. path2: A path-like object representing the second file system path. A path-like object is either a string or bytes object representing a path. Return Type: This method returns a Boolean value of class bool.
The filecmp module in python can be used to compare files and directories. 1. filecmp Compares the files file1 and file2 and returns True if identical, False if not.
os.path.samefile () method in Python is used to check whether the given two pathnames refer to the same file or directory or not. This is determined by comparing device number and i-node number of the given paths.
Find path to the given file using Python. We can get the location (path) of the running script file .py with __file__. __file__ is useful for reading other files and it gives the current location of the running file. It differs in versions.
You can use os.path.relpath
:
>>> path1 = "./base/folder1/subfolder"
>>> path2 = "./base/folder2/"
>>> import os
>>> os.path.relpath(path1, path2)
'../folder1/subfolder'
>>> os.path.relpath(path2, path1)
'../../folder2'
You want os.path.relpath
:
>>> import os
>>>
>>> path1 = "./base/folder1/subfolder"
>>> path2 = "./base/folder2/"
>>>
>>> os.path.relpath(path1, path2)
'../folder1/subfolder'
>>>
>>> os.path.relpath(path2, path1)
'../../folder2'
>>>
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