cd是用于更改工作目录的shell命令。

如何更改Python中的当前工作目录?


当前回答

如果您使用spyder和love GUI,只需单击屏幕右上角的文件夹按钮,即可浏览您希望作为当前目录的文件夹/目录。完成此操作后,您可以转到spyder IDE中窗口的文件资源管理器选项卡,您可以看到那里存在的所有文件/文件夹。检查当前工作目录转到spyder IDE的控制台,只需键入

pwd

它将打印与您之前选择的路径相同的路径。

其他回答

进一步了解Brian指出的方向,并基于sh(1.0.8+)

from sh import cd, ls

cd('/tmp')
print ls()

os.chdir()是正确的方法。

下面是一个上下文管理器更改工作目录的示例。它比其他地方提到的ActiveState版本更简单,但这可以完成任务。

上下文管理器:cd

import os

class cd:
    """Context manager for changing the current working directory"""
    def __init__(self, newPath):
        self.newPath = os.path.expanduser(newPath)

    def __enter__(self):
        self.savedPath = os.getcwd()
        os.chdir(self.newPath)

    def __exit__(self, etype, value, traceback):
        os.chdir(self.savedPath)

或者使用ContextManager尝试更简洁的等效方法(如下)。

实例

import subprocess # just to call an arbitrary command e.g. 'ls'

# enter the directory like this:
with cd("~/Library"):
   # we are in ~/Library
   subprocess.call("ls")

# outside the context manager we are back wherever we started.

我会这样使用os.chdir:

os.chdir("/path/to/change/to")

顺便说一句,如果需要计算当前路径,请使用os.getcwd()。

更多信息请点击此处

cd()使用生成器和装饰器很容易编写。

from contextlib import contextmanager
import os

@contextmanager
def cd(newdir):
    prevdir = os.getcwd()
    os.chdir(os.path.expanduser(newdir))
    try:
        yield
    finally:
        os.chdir(prevdir)

然后,即使抛出异常,目录也会恢复:

os.chdir('/home')

with cd('/tmp'):
    # ...
    raise Exception("There's no place like /home.")
# Directory is now back to '/home'.