python表示当前目录_从Python脚本获取当前目录的父项
使用os.path
要獲取包含腳本的目錄的父目錄(無論當(dāng)前工作目錄如何),您需要使用__file__.
from os.path import dirname, abspath
d = dirname(dirname(abspath(__file__))) # /home/kristina/desire-directory
基本上,您可以通過根據(jù)需要多次調(diào)用os.path.dirname來走向目錄樹.例:
In [4]: from os.path import dirname
In [5]: dirname('/home/kristina/desire-directory/scripts/script.py')
Out[5]: '/home/kristina/desire-directory/scripts'
In [6]: dirname(dirname('/home/kristina/desire-directory/scripts/script.py'))
Out[6]: '/home/kristina/desire-directory'
如果要獲取當(dāng)前工作目錄的父目錄,請(qǐng)使用os.getcwd:
import os
d = os.path.dirname(os.getcwd())
使用pathlib
您還可以使用pathlib模塊(可用于Python 3.4或更新版本).
每個(gè)pathlib.Path實(shí)例都有父屬性引用父目錄,以及parent屬性,它是路徑的祖先列表. Path.resolve可以用來獲得絕對(duì)路徑.它還解析所有符號(hào)鏈接,但如果不是所需的行為,則可以使用Path.absolute.
Path(__ file__)和Path()分別表示腳本路徑和當(dāng)前工作目錄,因此為了獲取腳本目錄的父目錄(不考慮當(dāng)前工作目錄),您將使用
from pathlib import Path
# `path.parents[1]` is the same as `path.parent.parent`
d = Path(__file__).resolve().parents[1] # Path('/home/kristina/desire-directory')
并獲取當(dāng)前工作目錄的父目錄
from pathlib import Path
d = Path().resolve().parent
請(qǐng)注意,d是一個(gè)Path實(shí)例,它并不總是方便.您可以在需要時(shí)輕松將其轉(zhuǎn)換為str:
In [15]: str(d)
Out[15]: '/home/kristina/desire-directory'
總結(jié)
以上是生活随笔為你收集整理的python表示当前目录_从Python脚本获取当前目录的父项的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python的闭包
- 下一篇: Python中的+=