如何在Python中更改工作目录(cd)?

2024-05-23 17:55:39 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: 命令目录cdshell
3条回答

您可以使用以下命令更改工作目录:

import os

os.chdir(path)

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

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

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

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

上下文管理器: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尝试more concise equivalent(below)

示例

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()

更多here

相关问题 更多 >