Categories
Python Answers

How to get the path of the current executed file in Python?

Spread the love

Sometimes, we want to get the path of the current executed file in Python.

In this article, we’ll look at how to get the path of the current executed file in Python.

How to get the path of the current executed file in Python?

To get the path of the current executed file in Python, we cajn use the inspect and os modules.

For instance, we write

from inspect import getsourcefile
from os.path import abspath

p = abspath(getsourcefile(lambda: 0))

to call getsourcefile to get the currently executing file.

We call it with a function that returns 0.

And then we call abspath to get the absolute path of the path returned by getsourcefile to get the full path.

Conclusion

To get the path of the current executed file in Python, we cajn use the inspect and os modules.

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 *