How to change the default working directory in python

若如初见. 提交于 2020-01-03 07:01:09

问题


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!!


回答1:


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__)).




回答2:


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.



来源:https://stackoverflow.com/questions/33691406/how-to-change-the-default-working-directory-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!