John Howard John Howard - 2 years ago 102
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?

Answer Source


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download