John Howard John Howard - 8 months ago 15
Python Question

Find current directory and file's directory

In Python what command can I use to find the current directory (where I was in terminal when executed) and where the file I am executing is?



The question asked for the directory of a given file, so the proper answer is:

import os 

To get the current working directory use os.getcwd() [Edit: as mentioned by the comment]

To find the path of the current directory file you can use the os module (os.path in particular) and os.path.realpath(__file__). To get the path of another file replace __file__ with a string containing the path of the file you wish to execute to determine its location.

realpath() returns the canonical path of specified file name.

For a full list of the os.path functions visit the manual.

If you use __file__ in a script that runs os.chdir(path), you must run the above line earlier than that, otherwise realpath() will use the new working directory.