patternpythonCritical
Find the current directory and file's directory
Viewed 0 times
directorycurrentthefindandfile
Problem
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?
Solution
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
To get the current working directory use
Documentation references for the modules, constants and functions used above:
import os
dir_path = os.path.dirname(os.path.realpath(__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 an os.chdir() call.)To get the current working directory use
import os
cwd = os.getcwd()Documentation references for the modules, constants and functions used above:
- The
osandos.pathmodules.
- The
__file__constant
os.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")
Code Snippets
import os
dir_path = os.path.dirname(os.path.realpath(__file__))import os
cwd = os.getcwd()Context
Stack Overflow Q#5137497, score: 4839
Revisions (0)
No revisions yet.