如何使用Python pathlib更改目录 [英] How can I change directory with Python pathlib

查看:57
本文介绍了如何使用Python pathlib更改目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Python pathlib (文档)功能?

假设我按如下方式创建Path对象:

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

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

import os
os.chdir(str(path))

解决方案

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

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

一个很好的选择是使用subprocess.Popen类的cwd参数,如 answer 所述./p>

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

What is the intended way to change directory using the Python pathlib (Documentation) functionality?

Lets assume I create a Path object as follows:

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

Currently I just know the following, but that seems to undermine the idea of pathlib.

import os
os.chdir(str(path))

解决方案

Based on the comments I realized that pathlib does not help changing directories and that directory changes should be avoided if possible.

Since I needed to call bash scripts outside of Python from the correct directory, I opted for using a context manager for a cleaner way of changing directories similar to this answer:

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)

A good alternative is to use the cwd parameter of the subprocess.Popen class as in this answer.

If you are using Python <3.6 and path is actually a pathlib.Path, you need str(path) in the chdir statements.

这篇关于如何使用Python pathlib更改目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆