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 280 views
1 answer 131 views
1 answer 179 views
2 answers 232 views
1 answer 223 views
1 answer 122 views
...