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

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


当前回答

下面是一个上下文管理器更改工作目录的示例。它比其他地方提到的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.

其他回答

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

pwd

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

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

Path中的Path对象(PyPI上提供的第三方包,不同于pathlib)为此提供了上下文管理器和chdir方法:

from path import Path  # pip install path

with Path("somewhere"):
    ...

Path("somewhere").chdir()

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'.
import os

abs_path = 'C://a/b/c'
rel_path = './folder'

os.chdir(abs_path)
os.chdir(rel_path)

您可以将两者与os.chdir(abs_path)或os.chdir(rel_path)一起使用,不需要调用os.getcwd()来使用相对路径。