[英]How can I get the script / exe directory with pathlib in python?
[英]How can I change directory with Python pathlib
使用 Python pathlib
(文檔)功能更改目錄的預期方法是什么?
假設我創建了一個Path
對象,如下所示:
from pathlib import Path
path = Path('/etc')
目前我只知道以下內容,但這似乎破壞了pathlib
的想法。
import os
os.chdir(str(path))
根據評論,我意識到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
實際上是一個pathlib.Path
,則您需要在chdir
語句中使用str(path)
。
在 Python 3.6 及以上版本中, os.chdir()
可以直接處理Path
對象。 實際上, Path
對象可以替換標准庫中的大多數str
路徑。
操作系統 chdir (path) 將當前工作目錄更改為 path。
該函數可以支持指定文件描述符。 描述符必須指向一個打開的目錄,而不是一個打開的文件。
3.3 新版功能:添加了在某些平台上將路徑指定為文件描述符的支持。
在 3.6 版更改: 接受一個path-like object 。
import os
from pathlib import Path
path = Path('/etc')
os.chdir(path)
這可能有助於將來不必與 3.5 或更低版本兼容的項目。
如果您不介意使用第三方庫:
$ 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`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.