snippetpythonCriticalCanonical
How do I get the full path of the current file's directory?
Viewed 0 times
directoryhowfullthecurrentfilepathget
Problem
How do I get the current file's directory path?
I tried:
But I want:
I tried:
>>> os.path.abspath(__file__)
'C:\\python27\\test.py'But I want:
'C:\\python27\\'Solution
The special variable
Python 3
For the directory of the script being run:
For the current working directory:
Python 2 and 3
For the directory of the script being run:
If you mean the current working directory:
Note that before and after
Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource),
References
__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?
Code Snippets
import pathlib
pathlib.Path(__file__).parent.resolve()import pathlib
pathlib.Path().resolve()import os
os.path.dirname(os.path.abspath(__file__))import os
os.path.abspath(os.getcwd())Context
Stack Overflow Q#3430372, score: 2815
Revisions (0)
No revisions yet.