Python relative path: The Complete Guide
If you’ve worked on a Python project that has more than one file, the possibilities are you’ve had to use an import statement before.
What is Relative Path
A relative path points to a location that is relative to a current directory. Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory.
Python relative path
The OS module in Python provides functions for interacting with the operating system. The os.path module is a sub-module of the OS module in Python used for common path name manipulation.
To set the relative path in Python, you can use the following code.
import os dirname = os.path.dirname(__file__) filename = os.path.join(dirname, 'your relative path to the file')
The above code will give you the absolute path to the file you’re looking for.
The os.path.relpath() is a built-in Python method used to get a relative filepath to the given path either from the current working directory or from the given directory.
import os path = "/Users/krunal/Desktop/code/pyt/database" start = "/Users/krunal" relative_path = os.path.relpath(path, start) print(relative_path)
Python: Absolute Path vs. Relative Path
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.
A relative path that depicts the location of a file or folder is relative to the current working directory. Unlike absolute paths, relative paths contain information that is only relative to the current document within the same website, which avoids the need to provide a full absolute path.
Absolute file paths start with a leading forward slash and describe how to access a given file or directory, starting from the root of the file system. Relative file paths do not start with a leading forward slash and are interpreted from the perspective of the current working directory.
If you don’t know where the user will be executing the script from, it is best to compute the absolute path on the user’s system using os and __file__. The __file__ is a global variable set on every Python script that returns the relative path to the *.py file that contains it.
Python relative path to absolute
To get an absolute file path in Python, use the os.path.abspath() function.
import os abspath = os.path.abspath("app.py") print(abspath)
That is it for this tutorial.