python中獲取當前以及上級路徑

2021-10-06 10:51:10 字數 653 閱讀 9489

python3.7.7

__file__表示當前.py檔案的路徑

os.path.dirname(__file__)表示當前.py檔案所在資料夾的路徑

os.path.dirname(os.path.dirname(__file__))表示上級目錄

os.path.dirname(os.path.dirname(os.path.dirname(__file__)))則表示上上級目錄

os.path.abspath('.')os.getcwd()一樣表示當前.終端所在資料夾的路徑

os.path.abspath('..')表示上級目錄

如有拼接其他路徑的需要可以使用os.path.abspath('.')+'/utils'或者os.path.join

注意,__file__在jupyter notebook中無效,在notebook中可是使用sys.path[0]獲取當前資料夾的路徑,然後os.path.dirname(sys.path[0])表示上級目錄

Python獲取當前目錄和上級目錄

import os print 獲取當前目錄 print os.getcwd print os.path.abspath os.path.dirname file file 為當前檔案,若果在ide中執行此行會報錯,可改為 d path.dirname 但是改為.後,就是獲得當前目錄,接著使用dir...

python獲取當前目錄路徑和上級路徑

在使用python的時候總會遇到路徑切換的使用情況,如想從資料夾test下的test.py呼叫data資料夾下的data.txt檔案 folder data data.txt test test.py一種方法可以在data檔案下加入 init py然後在test.py中import data就可以呼...

獲取當前目錄的上級目錄

獲取當前目錄的上級目錄path.getfullpath using system using system.collections.generic using system.linq using system.text using system.io namespace pathtest class...