如何知道/改变当前目录在Python shell?

我在Windows 7上使用Python 3.2。当我打开Python shell时,我如何知道当前目录是什么,以及如何将其更改为我的模块所在的另一个目录?

557559 次浏览

如果你import os,你可以使用os.getcwd来获取当前的工作目录,你可以使用os.chdir来改变你的目录

你可以使用os模块。

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

但如果它是关于寻找其他模块:你可以设置一个名为PYTHONPATH的环境变量,在Linux下会像这样

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

然后,解释器也在这里搜索imported模块。我猜在Windows下名字应该是一样的,但不知道怎么改。

编辑

Windows下:

set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib

(取自http://docs.python.org/using/windows.html)

编辑2

... 甚至更好:使用virtualenvvirtualenv_wrapper,这将允许你创建一个开发环境,在这个环境中,你可以根据自己的需要添加模块路径(add2virtualenv),而不会污染你的安装或“正常”的工作环境。

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

你想要的

import os
os.getcwd()
os.chdir('..')

改变当前目录不是在Python中寻找模块的方法。

相反,请参阅模块搜索路径的文档,了解Python如何找到要导入的模块。

下面是来自标准模块部分的相关位:

变量sys。路径是一个字符串列表,它决定 解释器的模块搜索路径。它被初始化为默认值 从环境变量PYTHONPATH获取的路径,或者从 如果未设置PYTHONPATH,则内置默认值。您可以使用 标准列表操作:

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

在回答关于获取和设置当前目录的原始问题时:

>>> 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.
>>> import os
>>> os.system('cd c:\mydir')

事实上,os.system()可以执行任何windows命令提示符可以执行的命令,而不仅仅是更改dir。

在python中更改当前工作目录最简单的方法是使用'os'包。下面是一个windows电脑的例子:

# Import the os package
import os


# Confirm the current working directory
os.getcwd()


# Use '\\' while changing the directory
os.chdir("C:\\user\\foldername")

你可以试试这个:

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"