如何使用Python pathlib更改目录

How can I change directory with Python pathlib

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

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

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

目前,我只知道以下内容,但这似乎破坏了pathlib的想法。

1
2
import os
os.chdir(str(path))


基于这些评论,我意识到pathlib不能帮助更改目录,并且应尽可能避免更改目录。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
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)

一个很好的选择是使用subprocess.Popen类的cwd参数,如此答案所示。

如果使用Python <3.6,而path实际上是pathlib.Path,则在chdir语句中需要str(path)


在Python 3.6或更高版本中,os.chdir()可以直接处理path对象。实际上,path对象可以替换标准库中的大多数str路径。

os.chdir(path) Change the current working directory to path.

This function can support specifying a file descriptor. The descriptor
must refer to an opened directory, not an open file.

New in version 3.3: Added support for specifying path as a file
descriptor on some platforms.

Changed in version 3.6: Accepts a path-like object.

1
2
3
4
5
import os
from pathlib import Path

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

这可能会在将来的项目中提供帮助,这些项目不必与3.5或更低版本兼容。


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

$ pip install path

然后:

1
2
3
4
5
6
from path import Path

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

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

1
2
Path("somewhere").cd()
# current working directory is now changed to `somewhere`