This question already has an answer here:
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?
This question already has an answer here:
In Python, what commands can I use to find:
To get the current directory full path:
1.To get the current directory full path
o/p:"C :\Users\admin\myfolder"
1.To get the current directory folder name alone
o/p:"myfolder"
If you are trying to find the current directory of the file you are currently in:
OS agnostic way:
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
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 anos.chdir()
call.)To get the current working directory use
Documentation references for the modules, constants and functions used above:
os
andos.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 pathnamepath
")os.getcwd()
(returns "a string representing the current working directory")os.chdir(path)
("change the current working directory topath
")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?
pathlib
module, introduced in Python 3.4 (PEP 428 — The pathlib module — object-oriented filesystem paths), makes path-related experience much much better.In order to get current working directory use
Path.cwd()
:To get an absolute path to your script file, use
Path.resolve()
method:And to get path of a directory where your script is located, access
.parent
(it is recommended to call.resolve()
before.parent
):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 otherPath
methods return path objects (PosixPath
in my case), not strings. In Python 3.4 and 3.5 that caused some pain, becauseopen
built-in function could only work with string or bytes objects, and did not supportPath
objects, so you had to convertPath
objects to strings or usePath.open()
method, but the latter option required you to change old code: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 toopen
function, so now you can passPath
objects toopen
function directly: