2934

How do I determine:

  1. the current directory (where I was in the shell when I ran the Python script), and
  2. where the Python file I am executing is?
Andy Lester
  • 91,102
  • 13
  • 100
  • 152
John Howard
  • 61,037
  • 23
  • 50
  • 66
  • 5
    `import os cwd = os.getcwd()` to pwd within python – Charlie Parker Dec 14 '22 at 19:14
  • This question is **blatantly** two questions in one and should have been closed as needing more focus. Both questions are simple reference questions, and thus ought to each have separate canonicals that this can be dupe-hammered with. However, I have been absolutely tearing my hair out trying to find a **proper** canonical for **only** the first question. I am turning up **countless** duplicates for the second question, most of which involve OP **not realizing there is a difference**. – Karl Knechtel Mar 15 '23 at 08:03
  • I have added the best I could find for "Q. How do I determine the current directory? A. Use `os.getcwd()`" after **literally hours** of searching. Ugh. – Karl Knechtel Mar 15 '23 at 08:40

13 Answers13

4587

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:

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Russell Dias
  • 70,980
  • 5
  • 54
  • 71
  • 194
    I hate it when I use this to append to sys.path. I feel so dirty right now. – FlipMcF Sep 26 '13 at 21:52
  • 13
    __file__ will not work if invoked from an IDE (say IDLE). Suggest os.path.realpath('./') or os.getcwd(). Best anser in here: http://stackoverflow.com/questions/2632199/how-do-i-get-the-path-of-the-current-executed-file-in-python?lq=1 – Neon22 Dec 20 '13 at 11:12
  • 3
    @Neon22 might suit some needs, but I feel it should be noted that those things aren't the same at all - files can be outside the working directory. – Mark Sep 15 '14 at 17:31
  • 1
    What about reversing the order, does it matter? `os.path.realpath(os.path.dirname(__file__))` – Moberg Oct 30 '14 at 12:55
  • 2
    @Moberg Often the paths will be the same when reversing `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
  • 7
    It gets an error `NameError: name '__file__' is not defined`. How to solve this? – Mohammad ElNesr Sep 26 '16 at 13:15
  • Apparently prepending to `sys.path` is acceptable according to the [documentation](https://docs.python.org/3.4/tutorial/modules.html#the-module-search-path). – neowulf33 Sep 15 '17 at 22:04
  • In some versions of python 2 (mainly windows versions) paths that include utf-8 characters (like emojis) will return with two question marks replacing the character from os functions, messing up any further commands that you try. – The Elemental of Destruction Jan 06 '19 at 10:05
  • @RusselDias why do you put `realpath` inside `dirname`? I tested each independently and they work like charm! – Minions Apr 13 '20 at 14:16
  • @MohammadElNesr are you sure that you're using `os.path.realpath` and not `os.path.abspath`? you're error eften occurs with `abspath`. – Minions Apr 13 '20 at 14:18
  • for jupyter notebooks - try os.path.realpath(os.getcwd()) (when you're in the right working directory) – Brndn Mar 22 '22 at 12:49
  • 1
    `os.path.dirname(__file__)` do the same that `os.path.dirname(os.path.realpath(__file__))` in my code – Hedwin Bonnavaud Aug 01 '22 at 11:37
  • 1
    Just make sure you use `"__file__"` – FaCoffee Sep 26 '22 at 15:19
  • I don't think the first parenthesis is correct at all. `__file__` seems to be absolute, not relative to the CWD – theonlygusti Jan 10 '23 at 02:03
378

Current working directory: os.getcwd()

And the __file__ attribute can help you find out where the file you are executing is located. This Stack Overflow post explains everything: How do I get the path of the current executed file in Python?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nix
  • 57,072
  • 29
  • 149
  • 198
356

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))
Community
  • 1
  • 1
Daniel Reis
  • 12,944
  • 6
  • 43
  • 71
284

The pathlib module, introduced in Python 3.4 (PEP 428 — The pathlib module — object-oriented filesystem paths), makes the path-related experience much much better.

pwd

/home/skovorodkin/stack

tree

.
└── scripts
    ├── 1.py
    └── 2.py

In order to get the 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 the Path.resolve() method:

print(Path(__file__).resolve())  # /home/skovorodkin/stack/scripts/1.py

And to get the 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 the Path.open() method, but the latter option required you to change old code:

File 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')

Output

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 the open function, so now you can pass Path objects to the open function directly:

python3.6 scripts/2.py

OK
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
skovorodkin
  • 9,394
  • 1
  • 39
  • 30
  • 7
    Note also that these methods are chainable, so you can use `app_path = Path(__file__).resolve().parent.parent.parent` as a parallel to `../../../` if you need to. – shacker Mar 18 '19 at 07:10
  • What system has executables (or the equivalent) by the name "`python3.5`" and "`python3.6`"? Ubuntu [Ubuntu MATE 20.04](https://en.wikipedia.org/wiki/Ubuntu_MATE#Releases) (Focal Fossa) doesn't (at least not by default). It has executables by the name "`python3`" and "`python2`" (but not "`python`" - which causes [some things to break](https://pmortensen.eu/world2/2019/12/08/arm-toolchain-ubuntu-19-04-black-magic-probe/#Python_blues_on_Ubuntu)) – Peter Mortensen Sep 06 '21 at 20:42
  • @PeterMortensen, thanks for the corrections. I don't remember if I actually had `python3.x` symlinks that time. Maybe I thought it would make snippets a bit clearer to the reader. – skovorodkin Sep 07 '21 at 16:06
81
  1. To get the current directory full path

    >>import os
    >>print os.getcwd()
    

    Output: "C :\Users\admin\myfolder"

  2. To get the current directory folder name alone

    >>import os
    >>str1=os.getcwd()
    >>str2=str1.split('\\')
    >>n=len(str2)
    >>print str2[n-1]
    

    Output: "myfolder"

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vinithravit
  • 843
  • 6
  • 2
  • 12
    better do it in one line, i think: `os.getcwd().split('\\')[-1]` – imkost Sep 06 '12 at 16:24
  • 60
    better to use os.sep rather than hardcode for Windows: os.getcwd().split(os.sep)[-1] – kkurian Dec 11 '12 at 08:24
  • 6
    the problem with this approach is that if you execute the script from a different directory, you will get that directory's name instead of the scripts', which may not be what you want. – airstrike Nov 05 '13 at 16:28
  • 1
    Right, the current directory which hosts your file may not be your CWD – f0ster Mar 03 '16 at 03:56
56

Pathlib can be used this way to get the directory containing the current script:

import pathlib
filepath = pathlib.Path(__file__).resolve().parent
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mathieu C.
  • 779
  • 5
  • 10
  • I like this solution. However can cause some Python 2.X issues. – Kimmo Hintikka Feb 16 '17 at 09:32
  • 1
    For python 3.3 and earlier pathlib has to be installed – A. Romeu Apr 05 '17 at 06:43
  • 7
    @Kimmo The only reason you should be working in Python 2 code is to convert it to Python 3. – kagronick May 30 '18 at 18:42
  • @kagnirick agreed, but there are still people who don't. I write all my new stuff with formatted string literals (PEP 498) using Python 3.6 so that someone doesn't go and push them to Python2. – Kimmo Hintikka May 31 '18 at 13:21
  • Note also that these methods are chainable, so you can use `app_path = Path(__file__).resolve().parent.parent.parent` as a parallel to `../../../` if you need to. – shacker Mar 18 '19 at 07:11
  • when i run the code in jupyter notebook, it has the error: `NameError: name '__file__' is not defined`, how to solve? – XYZ Sep 12 '22 at 04:47
43

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__))
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Kurt
  • 463
  • 4
  • 2
38

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.

Jazzer
  • 2,993
  • 1
  • 19
  • 24
38

To get the current directory full path:

os.path.realpath('.')
Logovskii Dmitrii
  • 2,629
  • 4
  • 27
  • 44
Ilia S.
  • 780
  • 7
  • 19
34

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__)
Blairg23
  • 11,334
  • 6
  • 72
  • 72
30

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())
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
StormShadow
  • 1,589
  • 4
  • 25
  • 33
17

If you're searching for the location of the currently executed script, you can use sys.argv[0] to get the full path.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Grochni
  • 1,663
  • 20
  • 25
17

For question 1, use os.getcwd() # Get working directory and os.chdir(r'D:\Steam\steamapps\common') # Set working directory


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 weird when compiled by PyInstaller, because magic properties are not set in __main__ level and sys.argv[0] is the way your executable was called (it means that it becomes affected by the working directory).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kotauskas
  • 1,239
  • 11
  • 31