Categories
Python Answers

How to get the absolute path from relative path in Python?

Spread the love

Sometimes, we want to get the absolute path from relative path in Python.

In this article, we’ll look at how to get the absolute path from relative path in Python.

How to get the absolute path from relative path in Python?

To get the absolute path from relative path in Python, we can use the os.path.join method.

For instance, we write

import os

dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, "relative/path/to/file/you/want")

to get the path of the current script’s directory with

dirname = os.path.dirname(__file__)

Then we call os.path.join to join the current script path with the relative path to return the absolute path.

Conclusion

To get the absolute path from relative path in Python, we can use the os.path.join method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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