I have an absolute path to file A.
I have a relative path to file B from file A's directory. This path may and will use ".." to go up the directory structure in arbitrarily complex ways.
Example A:
C:\projects\project1\module7\submodule5\fileA
Example Bs:
..\..\module3\submodule9\subsubmodule32\fileB
..\submodule5\fileB
..\..\module7\..\module4\submodule1\fileB
fileB
How do I combine the two in order to get the simplest possible absolute path to file B?
Use abspath() to Get the Absolute Path in Python abspath() with the given path to get the absolute path. The output of the abspath() function will return a string value of the absolute path relative to the current working directory.
An absolute path is a path that describes the location of a file or folder regardless of the current working directory; in fact, it is relative to the root directory.
In this case, first, we need the current script's path, and from it, we use dirname to get the directory path of the script file. Once we have that, we cd into the folder and print the working directory. To get the full or absolute path, we attach the basename of the script file to the directory path or $DIR_PATH.
An absolute path is defined as specifying the location of a file or directory from the root directory(/). In other words,we can say that an absolute path is a complete path from start of actual file system from / directory. Relative path is defined as the path related to the present working directly(pwd).
If I get your problem right, you could do something like this:
File a = new File("/some/abs/path"); File parentFolder = new File(a.getParent()); File b = new File(parentFolder, "../some/relative/path"); String absolute = b.getCanonicalPath(); // may throw IOException
String absolutePath = FileSystems.getDefault().getPath(mayBeRelativePath).normalize().toAbsolutePath().toString();
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