使用Python pathlib (Documentation)功能更改目录的预期方式是什么?
假设我创建了一个Path对象,如下所示:
from pathlib import Path
path = Path('/etc')目前我只知道以下几点,但这似乎破坏了pathlib的想法。
import os
os.chdir(str(path))发布于 2017-02-24 22:58:35
基于这些评论,我意识到pathlib无助于更改目录,如果可能,应该避免更改目录。
由于我需要从正确的目录中调用Python外部的bash脚本,因此我选择使用上下文管理器,以便以一种更简洁的方式更改目录,类似于下面的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)一个不错的替代方法是使用subprocess.Popen类的cwd参数,就像在这个answer中一样。
如果您使用的是Python <3.6,并且path实际上是一个pathlib.Path,那么您需要在chdir语句中使用str(path)。
发布于 2018-03-01 16:04:57
在Python3.6或更高版本中,os.chdir()可以直接处理Path对象。实际上,Path对象可以替换标准库中的大多数str路径。
path os.chdir(path)将当前工作目录更改为
。
此函数支持指定文件描述符。描述符必须引用打开的目录,而不是打开的文件。
版本3.3中的新功能:添加了在某些平台上将路径指定为文件描述符的支持。
版本3.6中的更改:接受path-like object。
import os
from pathlib import Path
path = Path('/etc')
os.chdir(path)这可能会对将来不需要与3.5或更低版本兼容的项目有所帮助。
发布于 2019-02-01 13:24:44
如果您不介意使用a third-party library
$ 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. 或者,如果您想在没有context manager的情况下完成此操作
Path("somewhere").cd()
# current working directory is now changed to `somewhere`https://stackoverflow.com/questions/41742317
复制相似问题