88

When I run the following script in IDLE

import os
print(os.getcwd())

I get output as

D:\testtool

but when I run from cmd prompt, I get

c:\Python33>python D:\testtool\current_dir.py
c:\Python33

How do I get same result which I got using IDLE ?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Shriram
  • 4,711
  • 6
  • 20
  • 22
  • This question is founded on a wrong premise; `os.getcwd()` is, indeed, how you get the current working directory. The problem is that **how you run the script changes what the current working directory is**. – Karl Knechtel Mar 15 '23 at 07:37
  • In other words: the direct answer to the question is "not by anything in the Python code, but by **using terminal commands to move to `D:\testtool`**, and then running `python current_dir.py`". – Karl Knechtel Mar 15 '23 at 07:54

3 Answers3

123

It seems that IDLE changes its current working dir to location of the script that is executed, while when running the script using cmd doesn't do that and it leaves CWD as it is.

To change current working dir to the one containing your script you can use:

import os
os.chdir(os.path.dirname(__file__))
print(os.getcwd())

The __file__ variable is available only if you execute script from file, and it contains path to the file. More on it here: Python __file__ attribute absolute or relative?

Community
  • 1
  • 1
Maciek
  • 3,174
  • 1
  • 22
  • 26
  • 1
    I would recommend against changing the directory as you might get non-deterministic results if the user expected to run the script from a different directory. – Frederick Ollinger Sep 02 '21 at 05:05
  • I agree with @FrederickOllinger, there is no need to change directory. ```os.path.dirname(__file__)``` is sufficient. – Ashley Kleynhans Jul 05 '22 at 13:50
22

Using pathlib you can get the folder in which the current file is located. __file__ is the pathname of the file from which the module was loaded. Ref: docs

import pathlib

current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)

Doc ref: link

Alen Siljak
  • 2,482
  • 2
  • 24
  • 29
butsyk
  • 237
  • 2
  • 6
  • 2
    Can't the current file location and the current working directory be different? – Stevoisiak Jun 24 '19 at 16:38
  • Yes, can you change the current working directory, cwd, with os.chdir(path). Change the current working directory to path. https://docs.python.org/3/library/os.html#os-file-dir – Frederick Ollinger Aug 13 '22 at 16:59
11

Python's default pathlib library provides the cwd like so:

import pathlib

pathlib.Path.cwd()
iacob
  • 20,084
  • 6
  • 92
  • 119