How can I change directory with Python pathlib
使用Python
假设我创建一个
1 2 | from pathlib import Path path = Path('/etc') |
目前,我只知道以下内容,但这似乎破坏了
1 2 | import os os.chdir(str(path)) |
基于这些评论,我意识到
由于我需要从正确的目录中调用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) |
一个很好的选择是使用
如果使用Python <3.6,而
在Python 3.6或更高版本中,
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或更低版本兼容。
如果您不介意使用第三方库:
然后:
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` |