How do I get the path and name of the file that is currently executing

0 votes

I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.

For example, let's say I have three files. Using execfile:

  • script_1.py calls script_2.py.
  • In turn, script_2.py calls script_3.py.

How can I get the file name and path of script_3.pyfrom code within script_3.py, without having to pass that information as arguments from script_2.py?

May 11, 2020 in Python by kartik
• 37,510 points
2,293 views

1 answer to this question.

0 votes

Hello @kartik,

Since Python 3 is fairly mainstream, I wanted to include a pathlib answer, as I believe that it is probably now a better tool for accessing file and path information.

from pathlib import Path

current_file: Path = Path(__file__).resolve()

If you are seeking the directory of the current file, it is as easy as adding .parent to the Path() statement:

current_path: Path = Path(__file__).parent.resolve()

Thank You!!

answered May 11, 2020 by Niroj
• 82,880 points

Related Questions In Python

0 votes
1 answer

In NumPy how do I get the maximum of subsets? Python

You can use np.maximum.reduceat: >>> _, idx = np.unique(g, ...READ MORE

answered Nov 9, 2018 in Python by Nymeria
• 3,560 points
1,279 views
0 votes
1 answer

how do i get the list of all the keys in my dictionary?

my_dict = {'one': 'first', 'two': 'second', 'three': ...READ MORE

answered Sep 30, 2020 in Python by VJ_python
523 views
0 votes
0 answers
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,023 views
0 votes
1 answer
0 votes
1 answer

How can I get the domain name of my site within a Django template?

Hello kartik, The variation of the context processor ...READ MORE

answered Apr 23, 2020 in Python by Niroj
• 82,880 points
9,328 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP