HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCriticalCanonical

Find the current directory and file's directory

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
directoryandfindthecurrentfile

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:

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 os and os.path modules.



  • 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 pathname path")



  • os.getcwd() (returns "a string representing the current working directory")



  • os.chdir(path) ("change the current working directory to path")

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.