How do I get the full path of the current file's directory?
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Intrigue Looping
--
Chapters
00:00 How Do I Get The Full Path Of The Current File'S Directory?
00:17 Accepted Answer Score 2743
01:34 Answer 2 Score 18
01:41 Answer 3 Score 203
02:02 Answer 4 Score 112
02:32 Thank you
--
Full question
https://stackoverflow.com/questions/3430...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #directory
#avk47
ACCEPTED ANSWER
Score 2743
The special variable __file__ contains the path to the current file. From that we can get the directory using either pathlib or the os.path module.
Python 3
For the directory of the script being run:
import pathlib
pathlib.Path(__file__).parent.resolve()
For the current working directory:
import pathlib
pathlib.Path().resolve()
Python 2 and 3
For the directory of the script being run:
import os
os.path.dirname(os.path.abspath(__file__))
If you mean the current working directory:
import os
os.path.abspath(os.getcwd())
Note that before and after file is two underscores, not just one.
Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource), __file__ may not be set since there is no notion of "current file". The above answer assumes the most common scenario of running a python script that is in a file.
References
- pathlib in the python documentation.
 - os.path - Python 2.7, os.path - Python 3
 - os.getcwd - Python 2.7, os.getcwd - Python 3
 - what does the __file__ variable mean/do?
 
ANSWER 2
Score 203
Using Path from pathlib is the recommended way since Python 3:
from pathlib import Path
print("File      Path:", Path(__file__).absolute())
print("Directory Path:", Path().absolute()) # Directory of current working directory, not __file__  
Note: If using Jupyter Notebook, __file__ doesn't return expected value, so Path().absolute() has to be used.
ANSWER 3
Score 112
In Python 3.x I do:
from pathlib import Path
path = Path(__file__).parent.absolute()
Explanation:
Path(__file__)is the path to the current file..parentgives you the directory the file is in..absolute()gives you the full absolute path to it.
Using pathlib is the modern way to work with paths. If you need it as a string later for some reason, just do str(path).
ANSWER 4
Score 18
import os
print(os.path.dirname(__file__))