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

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


当前回答

您可以通过以下方式更改工作目录:

import os

os.chdir(path)

使用此方法时,需要遵循两个最佳实践:

捕获无效路径上的异常(WindowsError、OSError)。如果抛出异常,请不要执行任何递归操作,尤其是破坏性操作。他们将在旧的道路上运行,而不是在新的道路上。完成后返回到旧目录。这可以通过将chdir调用包装在上下文管理器中以异常安全的方式完成,就像BrianM.Hunt在回答中所做的那样。

在子流程中更改当前工作目录不会更改父流程中的当前工作目录。Python解释器也是如此。不能使用os.chdir()更改调用进程的CWD。

其他回答

如果您想执行类似“cd..”选项的操作,只需键入:

os.chdir(“..”)

它与Windows cmd:cd中的相同。。当然,导入os是必要的(例如,键入它作为代码的第一行)

如果您使用的是相对较新的Python版本,也可以使用上下文管理器,例如:

from __future__ import with_statement
from grizzled.os import working_directory

with working_directory(path_to_directory):
    # code in here occurs within the directory

# code here is in the original directory

更新

如果你喜欢自己动手:

import os
from contextlib import contextmanager

@contextmanager
def working_directory(directory):
    owd = os.getcwd()
    try:
        os.chdir(directory)
        yield directory
    finally:
        os.chdir(owd)

os.chdir()是cd的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.

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