How do I determine:
- the current directory (where I was in the shell when I ran the Python script), and
- where the Python file I am executing is?
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.
To get the full path to the directory a Python file is contained in, write this in that file:
(Note that the incantation above won’t work if you’ve already used
os.chdir()to change your current working directory, since the value of the__file__constant is relative to the current working directory and is not changed by anos.chdir()call.)To get the current working directory use
Documentation references for the modules, constants and functions used above:
osandos.pathmodules.__file__constantos.path.realpath(path)(returns “the canonical path of the specified filename, eliminating any symbolic links encountered in the path”)os.path.dirname(path)(returns “the directory name of pathnamepath“)os.getcwd()(returns “a string representing the current working directory”)os.chdir(path)(“change the current working directory topath“)