Get the absolute file path in Python
This post explains how you can get an absolute file path in Python. But before that let’s see what an absolute path really is.
Generally, a path that specifies the entire path to a file, directory, or folder is considered an absolute path. In this path, we begin at the home directory of our computer and end with the file, directory, or folder we wish to access. By using absolute paths, Python is able to locate the exact file you want to access. Here is an example of the absolute path for better understanding:
See, how it specifies the path you took to reach your
So, now we know what an absolute path is, lets now discuss getting an absolute file path in detail:
There are different types of operating systems, such as Windows, Linux, or macOS. These operating systems have different paths for storing files. The first step in running Python scripts on these machines is to find the absolute path to the files or directories automatically rather than hardcoding it for each system. On Linux and macOS, an absolute path begins with / and on Windows with C:/.
Python method for finding the absolute path:
Using Python, you will find the complete path of the file you want automatically and don’t need to hardcode everything. First, follow the OS module to find out where
src/example.docis in relation to the current file that you are working on.
Before using import make sure you have the os module installed on your computer. If not, follow
pip install os-syson your terminal.
import os os.path.abspath("src/example.doc")
Here first you will import the
OS Module which Interfaces with the operating system.
Then we will use the
os.pathlibrary to return an absolutized version of the path.
The benefit of getting an absolute path is that you are able to return the correct path for files or folders on different operating systems. Using the
os.path.abspath library, you can get an absolute path in Python. With this example, we have concluded our tutorial.
Do you want to know how you iterate over the NumPy array? Follow this tutorial: Iterating Over a NumPy Array