How do I get the current file’s directory path?
I tried:
>>> os.path.abspath(__file__)
'C:\\python27\\test.py'
But I want:
'C:\\python27\\'
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The special variable
__file__contains the path to the current file. From that we can get the directory using eitherpathlibor theos.pathmodule.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
fileis 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