How do to get the path and name of the file that is currently executing in Python

3 Answers

0 votes
import os

print(os.path.realpath(__file__))



'''
run:

/home/examples/main.py

'''

 



answered Jun 7, 2023 by avibootz
0 votes
import inspect, os

print("Filename:", inspect.getfile(inspect.currentframe())) 
print("Directory:", os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) 



'''
run:

Filename: main.py
Directory: /home/examples

'''

 



answered Jun 7, 2023 by avibootz
edited Jun 7, 2023 by avibootz
0 votes
import inspect, os

print(os.path.abspath(inspect.stack()[0][1])) 
print("Directory:", os.path.dirname(os.path.abspath(inspect.stack()[0][1]))) 
print("FileName:", inspect.stack()[0][1])



'''
run:

/home/examples/main.py
Directory: /home/examples
FileName: main.py

'''

 



answered Jun 7, 2023 by avibootz

Related questions

1 answer 372 views
1 answer 217 views
1 answer 273 views
2 answers 375 views
1 answer 344 views
1 answer 201 views
...