53

pathlib 使用 Python (文档)功能更改目录的预期方法是什么?

假设我创建了一个Path对象,如下所示:

from pathlib import Path
path = Path('/etc')

目前我只知道以下内容,但这似乎破坏了pathlib.

import os
os.chdir(str(path))
4

3 回答 3

46

根据评论,我意识到这pathlib无助于更改目录,如果可能的话,应该避免更改目录。

由于我需要从正确的目录调用 Python 之外的 bash 脚本,因此我选择使用上下文管理器来以更简洁的方式更改类似于此答案的目录:

import os
import contextlib
from pathlib import Path

@contextlib.contextmanager
def working_directory(path):
    """Changes working directory and returns to previous on exit."""
    prev_cwd = Path.cwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(prev_cwd)

一个很好的选择是使用这个答案中的类cwd参数。subprocess.Popen

如果您使用的是 Python <3.6 并且path实际上是 a pathlib.Path,则需要str(path)chdir语句中。

于 2017-02-24T14:58:35.060 回答
18

在 Python 3.6 以上,os.chdir()可以直接处理Path对象。事实上,该Path对象可以替换str标准库中的大多数路径。

操作系统。chdir (path) 将当前工作目录更改为路径。

该函数可以支持指定文件描述符。描述符必须引用打开的目录,而不是打开的文件。

3.3 版中的新功能:添加了对在某些平台上将路径指定为文件描述符的支持。

在 3.6 版更改: 接受类似路径的对象

import os
from pathlib import Path

path = Path('/etc')
os.chdir(path)

这可能有助于将来不必与 3.5 或更低版本兼容的项目。

于 2018-03-01T08:04:57.307 回答
3

如果您不介意使用第三方库

$ pip install path

然后:

from path import Path

with Path("somewhere"):
    # current working directory is now `somewhere`
    ...
# current working directory is restored to its original value. 

或者如果您想在没有上下文管理器的情况下执行此操作:

Path("somewhere").cd()
# current working directory is now changed to `somewhere`
于 2019-02-01T05:24:43.663 回答