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:

  • calls
  • In turn, calls

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

May 11 in Python by kartik
• 27,140 points

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 by Niroj
• 58,500 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,520 points
0 votes
0 answers

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

can you give an example? with the ...READ MORE

May 6, 2019 in Python by Waseem
• 4,540 points
0 votes
0 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 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,356 views
0 votes
0 answers
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 in Python by Niroj
• 58,500 points