1

I have a quick question about the default working directly on python. I am currently using the python 2.7. In this case the default working directly is the C:/Python27. I want to change this permanently to another directory. Even if we write down following on shell, the default working directory will go back to the original C:/Python27 automatically.

import os

os.chdir('a path')

Does any one know how to set up default directory permanently to "the path" which keeps the directory after the closing the shell? This is a different question from how to change working directory just by the function temporarily.
Thank you so much for your help!!

Wave
  • 111
  • 1
  • 3
  • 12
  • 1
    How are you launching your script? – Martin Evans Nov 13 '15 at 11:17
  • You mean when you double-click `python.exe` or write `python` in the console? – Torxed Nov 13 '15 at 11:26
  • When you start Python, a new environment is created - so when you change the current working directory, it is effectively changed in this environment ; however when closing Python the original environment is restored. You can't do what you want in Windows there is no bash `source` equivalent. – mguijarr Nov 13 '15 at 13:01
  • Possible duplicate of [How to set the current working directory in Python?](http://stackoverflow.com/questions/1810743/how-to-set-the-current-working-directory-in-python) – Trevor Boyd Smith Mar 22 '17 at 13:44
  • @TrevorBoydSmith It is different question totally. I used os.chdir but it still goes back to the default working directory after closing and relaunch program. Did you put -1? – Wave Mar 24 '17 at 04:33

2 Answers2

4

The working directory of the python directory is the directory from which it was started. If from a console (cmd.exe) I do cd /some/dir and then start python, its working directory will be /some/dir.

If you want an interactive console started at a given directory you have some options:

  • Using a shortcut, you can change its Start in field, in the properties tab, to point to your target directory.
  • Use IPython instead, and add a startup script to the default profile so it always start at the target directory. IPython is an enhanced interactive with lots of useful features.

If you are running from a script and want to switch to the folder where you script is stored, you could use os.cd(os.path.dirname(__file__)).

memoselyk
  • 3,993
  • 1
  • 17
  • 28
  • Thanks so much for your help! i decided to use IDE pycharm then i can keep working on a directory on where i want to work. – Wave Nov 18 '15 at 09:36
0

If you are launching Python from the start menu of Windows, right click on the icon and select more -> file location.

Once there you can right click on the shortcut and select properties. From there you should be able to define the 'Start in:' location.

cebess
  • 11
  • 4