232

I am using Python 3.2 on Windows 7. When I open the Python shell, how can I know what the current directory is and how can I change it to another directory where my modules are?

astay13
  • 6,137
  • 8
  • 36
  • 52
  • This has already been discussed [here] [1]: http://stackoverflow.com/questions/431684/how-do-i-cd-in-python – mudda Nov 23 '11 at 20:11
  • 5
    @astay13 -- I think Ignacio means that you aren't intended to change directory to your module-path. You should probably check out the PYTHONPATH environment variable. – simon Nov 23 '11 at 20:12
  • Classical XY problem – M.D. May 21 '21 at 07:16

7 Answers7

324

You can use the os module.

>>> import os
>>> os.getcwd()
'/home/user'
>>> os.chdir("/tmp/")
>>> os.getcwd()
'/tmp'

But if it's about finding other modules: You can set an environment variable called PYTHONPATH, under Linux would be like

export PYTHONPATH=/path/to/my/library:$PYTHONPATH

Then, the interpreter searches also at this place for imported modules. I guess the name would be the same under Windows, but don't know how to change.

edit

Under Windows:

set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib

(taken from http://docs.python.org/using/windows.html)

edit 2

... and even better: use virtualenv and virtualenv_wrapper, this will allow you to create a development environment where you can add module paths as you like (add2virtualenv) without polluting your installation or "normal" working environment.

http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html

wal-o-mat
  • 6,238
  • 6
  • 28
  • 37
  • Do I have to set PYTHONPATH in the Windows command line or in the Python shell? – astay13 Nov 23 '11 at 20:17
  • @simon ;) astay13: You have to set it in the command line, but I guess there is a graphical menu for making it persistent (otherwise you have to re-set it everytime you reboot or some such, in my case everytime I log in). – wal-o-mat Nov 23 '11 at 20:22
  • @astay13: on Windows you can set it as a global environment variable. Don't have a Windows system to check on right now, but I think you can find it under "Control Panel -> System" -- it's in there somewhere :) – simon Nov 23 '11 at 20:24
  • 2
    @astray13: You also have the option of ignoring the environment variable and instead appending to `sys.path` inside of your script. – Steven Rumbalski Nov 23 '11 at 20:31
  • 3
    @astay13: don't set `PYTHONPATH` globally if you have more than one Python installed (or have programs installed that bundle Python with them -- in other words you'll never know): it may break your installation in [mysterious ways](http://stackoverflow.com/q/23130614/4279) – jfs Apr 22 '14 at 04:21
21

you want

import os
os.getcwd()
os.chdir('..')
simon
  • 12,663
  • 4
  • 40
  • 64
  • 1
    os.chdir('C:\Users\Ajeya\Documents\') ^ SyntaxError: EOL while scanning string literal – AAI Sep 04 '16 at 00:31
  • 2
    @Whatever, you need to double up backslashes if you use them in a regular (non-raw) Python string. Python also lets you use forward slashes instead. Thus, either `os.chdir('C:/Users/Ajeya/Documents')`, or `os.chdir('C:\\Users\\Ajeya\\Documents')`, or `os.chdir(r'C:\Users\Ajeya\Documents')`. – Charles Duffy Oct 13 '17 at 19:31
  • It would be good to note that you call `os.getcwd()` only for debugging purposes so that we can see what the working directory is before we change it. The code to actually change the `cwd` is just `os.chdir('..')` – Toothpick Anemone Mar 21 '18 at 21:18
15
>>> import os
>>> os.system('cd c:\mydir')

In fact, os.system() can execute any command that windows command prompt can execute, not just change dir.

Tim Cooper
  • 144,163
  • 35
  • 302
  • 261
shankar_pratap
  • 943
  • 7
  • 7
  • File "", line 1 os.system('cd c:\Users\Ajeya\Documents\') ^ SyntaxError: EOL while scanning string literal – AAI Sep 04 '16 at 00:32
6

The easiest way to change the current working directory in python is using the 'os' package. Below there is an example for windows computer:

# Import the os package
import os

# Confirm the current working directory 
os.getcwd()

# Use '\\' while changing the directory 
os.chdir("C:\\user\\foldername")
Rem-D
  • 513
  • 5
  • 8
sambeet
  • 81
  • 1
  • 1
  • use of "\\" and clarification about Windows computer. But I agree the accepted answer is more descriptive. – sambeet Jun 14 '17 at 12:00
6

Changing the current directory is not the way to deal with finding modules in Python.

Rather, see the docs for The Module Search Path for how Python finds which module to import.

Here is a relevant bit from Standard Modules section:

The variable sys.path is a list of strings that determines the interpreter’s search path for modules. It is initialized to a default path taken from the environment variable PYTHONPATH, or from a built-in default if PYTHONPATH is not set. You can modify it using standard list operations:

>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')

In answer your original question about getting and setting the current directory:

>>> help(os.getcwd)

getcwd(...)
    getcwd() -> path

    Return a string representing the current working directory.

>>> help(os.chdir)

chdir(...)
    chdir(path)

    Change the current working directory to the specified path.
Steven Rumbalski
  • 39,949
  • 7
  • 78
  • 111
  • This answer is gold.. Just add your project directory like this:```import sys sys.path.append('/home/g/PycharmProjects/your_project/') ``` – gies0r Dec 30 '18 at 20:54
4

If you import os you can use os.getcwd to get the current working directory, and you can use os.chdir to change your directory

deontologician
  • 2,626
  • 1
  • 19
  • 31
0

You can try this:

import os

current_dir = os.path.dirname(os.path.abspath(__file__))   # Can also use os.getcwd()
print(current_dir)                                         # prints(say)- D:\abc\def\ghi\jkl\mno"
new_dir = os.chdir('..\\..\\..\\')                         
print(new_dir)                                             # prints "D:\abc\def\ghi"