252

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

4

7 回答 7

353

您可以使用该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

...甚至更好:使用virtualenvand virtualenv_wrapper,这将允许您创建一个开发环境,您可以在其中添加您喜欢的模块路径 ( add2virtualenv),而不会污染您的安装或“正常”工作环境。

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

于 2011-11-23T20:08:54.613 回答
22

你要

import os
os.getcwd()
os.chdir('..')
于 2011-11-23T20:09:09.323 回答
16
>>> import os
>>> os.system('cd c:\mydir')

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

于 2012-03-28T18:23:04.607 回答
9

在 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")
于 2017-06-07T08:39:04.510 回答
6

更改当前目录不是处理在 Python 中查找模块的方法。

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

这是标准模块部分的相关内容:

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

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

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

>>> 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.
于 2011-11-23T20:13:00.130 回答
3

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

于 2011-11-23T20:08:32.980 回答
1

你可以试试这个:

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"


于 2019-08-14T09:58:49.547 回答