Get Absolute Path in Python

Python absolute path

We often use files to store the outputs of our programs in permanent storage. Generally, we work with relative paths of files in our programs. In this article, we will discuss two ways to get the absolute path to a file in python from its relative pathname.

What is an absolute path to a file?

The absolute path to a file is the entire file path from the root file to the current file. For instance, Look at the following image. 

file-path image

You can observe that the sample.txt path is present in the java2blog folder. The java2blog folder is present in the codes folder.

Here, the absolute path of the file sample.txt will always be “/home/aditya1117/codes/java2blog/sample.txt”

On the other hand, its relative path will always change according to the folder from which we are viewing the file.  For instance, 

  • If we are currently in the java2blog folder, the relative path of the file will be /sample.txt.
  • However, If we move to the folder codes, the relative path to the file sample.txt will be /java2blog/sample.txt.

So, the relative path to a file changes according to the folder we are currently in. Whereas, the absolute path to a file never changes until the file is moved to another location. We can access the file using the absolute path from any directory. Whereas, we will have to update the relative path if we move to any other directory even if the file is at the same location.

How to get absolute path in Python

Let us now look at the ways to get the absolute path to a file in python.

Use abspath to get the absolute path to file

The os module in python provides us with the abspath() method under the os.path property. The abspath() method takes the relative path to a file and returns the absolute path in the string format as shown in the following example.

Output:

Here, the sample.txt file is present in the same folder as our source code file. So, the relative file has been given as only the file name.

use pathlib module to get the absolute path to file

Instead of using the os module, we can use the pathlib module to get the absolute path to a file in python. Here, we will use the Path() function and the absolute() method to get the absolute path to a file.

The Path() function takes the file name as input and creates a path object.  We can invoke the absolute() method on the path object to get the absolute path to a given file as follows.

Output:

Conclusion

In this article, we have discussed the relative path and the absolute path to a file. We have also discussed two approaches to get the absolute path in python. You can choose any of the approaches according to your preference as both the approaches have almost the same cost of execution.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *