How to know/change current directory in Python shell?

astay13 picture astay13 · Nov 23, 2011 · Viewed 468.7k times · Source

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?

Answer

wal-o-mat picture wal-o-mat · Nov 23, 2011

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