In Python, what commands can I use to find:
- the current directory (where I was in the terminal when I ran the Python script), and
- where the file I am executing is?
Join Stack Overflow to learn, share knowledge, and build your career.
In Python, what commands can I use to find:
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:
os
and os.path
modules.__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 pathname path
")os.getcwd()
(returns "a string representing the current working directory")os.chdir(path)
("change the current working directory to path
")realpath
with dirname
, but it will differ when the file (or its directory) is actually a symbolic link.
– Lekensteyn
Mar 17 '15 at 17:00
NameError: name '__file__' is not defined
. How to solve this?
– Mohammad ElNesr
Sep 26 '16 at 13:15
Current Working Directory: os.getcwd()
And the __file__
attribute can help you find out where the file you are executing is located. This SO post explains everything: How do I get the path of the current executed file in Python?
You may find this useful as a reference:
import os
print("Path at terminal when executing this file")
print(os.getcwd() + "\n")
print("This file path, relative to os.getcwd()")
print(__file__ + "\n")
print("This file full path (following symlinks)")
full_path = os.path.realpath(__file__)
print(full_path + "\n")
print("This file directory and name")
path, filename = os.path.split(full_path)
print(path + ' --> ' + filename + "\n")
print("This file directory only")
print(os.path.dirname(full_path))
__file__
signifies here? It does not work for me.
– Alex Raj Kaliamoorthy
Jun 17 '16 at 15:22
__file__
is an attribute of the module object. You need run the code inside a Python file, not on the REPL.
– Daniel Reis
Jun 20 '16 at 13:07
pathlib
module, introduced in Python 3.4 (PEP 428 — The pathlib module — object-oriented filesystem paths), makes path-related experience much much better.
$ pwd
/home/skovorodkin/stack
$ tree
.
└── scripts
├── 1.py
└── 2.py
In order to get current working directory use Path.cwd()
:
from pathlib import Path
print(Path.cwd()) # /home/skovorodkin/stack
To get an absolute path to your script file, use Path.resolve()
method:
print(Path(__file__).resolve()) # /home/skovorodkin/stack/scripts/1.py
And to get path of a directory where your script is located, access .parent
(it is recommended to call .resolve()
before .parent
):
print(Path(__file__).resolve().parent) # /home/skovorodkin/stack/scripts
Remember that __file__
is not reliable in some situations: How do I get the path of the current executed file in Python?.
Please note, that Path.cwd()
, Path.resolve()
and other Path
methods return path objects (PosixPath
in my case), not strings. In Python 3.4 and 3.5 that caused some pain, because open
built-in function could only work with string or bytes objects, and did not support Path
objects, so you had to convert Path
objects to strings or use Path.open()
method, but the latter option required you to change old code:
$ cat scripts/2.py
from pathlib import Path
p = Path(__file__).resolve()
with p.open() as f: pass
with open(str(p)) as f: pass
with open(p) as f: pass
print('OK')
$ python3.5 scripts/2.py
Traceback (most recent call last):
File "scripts/2.py", line 11, in <module>
with open(p) as f:
TypeError: invalid file: PosixPath('/home/skovorodkin/stack/scripts/2.py')
As you can see open(p)
does not work with Python 3.5.
PEP 519 — Adding a file system path protocol, implemented in Python 3.6, adds support of PathLike
objects to open
function, so now you can pass Path
objects to open
function directly:
$ python3.6 scripts/2.py
OK
app_path = Path(__file__).resolve().parent.parent.parent
as a parallel to ../../../
if you need to.
– shacker
Mar 18 '19 at 7:10
1.To get the current directory full path
>>import os
>>print os.getcwd()
o/p:"C :\Users\admin\myfolder"
1.To get the current directory folder name alone
>>import os
>>str1=os.getcwd()
>>str2=str1.split('\\')
>>n=len(str2)
>>print str2[n-1]
o/p:"myfolder"
If you are trying to find the current directory of the file you are currently in:
OS agnostic way:
dirname, filename = os.path.split(os.path.abspath(__file__))
If you're using Python 3.4, there is the brand new higher-level pathlib
module which allows you to conveniently call pathlib.Path.cwd()
to get a Path
object representing your current working directory, along with many other new features.
More info on this new API can be found here.
pathlib2
: pypi.python.org/pypi/pathlib2
– Eyal Levin
Oct 17 '17 at 14:54
Pathlib can be used this way to get the directory containing current script :
import pathlib
filepath = pathlib.Path(__file__).resolve().parent
app_path = Path(__file__).resolve().parent.parent.parent
as a parallel to ../../../
if you need to.
– shacker
Mar 18 '19 at 7:11
To get the current directory full path:
os.path.realpath('.')
os.getcwd()
and `os.path.realpath('.') return exactly the same string path.
– Leevo
Jan 21 '19 at 8:56
Answer to #1:
If you want the current directory, do this:
import os
os.getcwd()
If you want just any folder name and you have the path to that folder, do this:
def get_folder_name(folder):
'''
Returns the folder name, given a full folder path
'''
return folder.split(os.sep)[-1]
Answer to #2:
import os
print os.path.abspath(__file__)
A bit late to the party, but I think the most succinct way to find just the name of your current execution context would be
current_folder_path, current_folder_name = os.path.split(os.getcwd())
If you're searching for the location of the currently executed script, you can use sys.argv[0]
to get the full path.
sys.argv[0]
needn't contain the full path to the executing script.
– Mark Amery
Jul 31 '16 at 10:23
For question 1 use os.getcwd() # get working dir
and os.chdir(r'D:\Steam\steamapps\common') # set working dir
I recommend using sys.argv[0]
for question 2 because sys.argv
is immutable and therefore always returns the current file (module object path) and not affected by os.chdir()
. Also you can do like this:
import os
this_py_file = os.path.realpath(__file__)
# vvv Below comes your code vvv #
but that snippet and sys.argv[0]
will not work or will work wierd when compiled by PyInstaller because magic properties are not set in __main__
level and sys.argv[0]
is the way your exe was called (means that it becomes affected by the working dir).