如何在 Python 中獲取當前檔案目錄的完整路徑?


Python 的 OS 模組包含用於建立和刪除目錄(資料夾)、檢索其內容、更改和識別當前目錄等的功能。為了與底層作業系統互動,您必須首先匯入 os 模組。

可以在 Python 中獲取正在執行的程式程式碼的位置(路徑)。py 使用 __file__。__file__ 可用於根據當前檔案的位置讀取其他檔案。

示例

在以下示例中,os.getcwd() 函式生成一個包含 Python 正在執行的當前工作目錄的絕對路徑的字串 str。

#Python program to get the path of the current working directory #Program to get the path of the file #Using getcwd() #Importing the os module import os print(' The current working directory is: ', os.getcwd()) print('File name is: ', __file__)

輸出

執行上述程式後,將生成以下輸出。

The current working directory: C:\Users\pranathi\Desktop\python prog
File name: c:\users\pranathi\desktop\python prog\untitled1.py

使用 os.path.basename()

在 Python 中,os.path.basename() 方法用於獲取路徑的基本名稱。此方法在內部使用 os.path.split() 方法將提供的路徑拆分為一對(head,tail)。在將提供的路徑拆分為(head,tail)對後,os.path.basename() 方法返回 tail 部分。

示例

在以下示例中,os.path.dirname() 方法用於從提供的路徑中檢索目錄名稱。

#python program to find the basename and dirname of the path import os print('basename of the file: ', os.path.basename(__file__)) print('dirname of the file: ', os.path.dirname(__file__))

輸出

執行上述程式後,將生成以下輸出。

basename of the file: untitled1.py
dirname of the file: c:\users\pranathi\desktop\python prog

獲取目錄的絕對路徑

絕對路徑是指檔案或資料夾的位置,無論當前工作目錄如何;實際上,它是相對於根目錄的。

示例

以下示例是一個用於查詢絕對路徑的 python 程式。

#python program to find the absolute path import os print('absolute path of the file: ', os.path.abspath(__file__)) print('absolute path of dirname: ', os.path.dirname(os.path.abspath(__file__)))

在 python 中使用 os.getcwd 方法

OS 模組的 getcwd() 方法返回一個包含當前工作目錄的絕對路徑的字串。輸出字串中不包含尾部斜槓字元。

示例

在以下示例中,匯入了 os 模組,並使用 getcwd() 函式獲取當前工作目錄。目錄使用 print() 函式列印。

#importing the os module import os #to get the current working directory directory = os.getcwd() print(directory)

輸出

執行上述程式後,將生成以下輸出。

C:\Users\pranathi\Desktop\python prog

示例

輸出將根據您所在的目錄而有所不同,但它始終以根資料夾(例如,D:) 和以 a 為字首的目錄開頭。

import os absolute_path = os.path.abspath(__file__) print("Full path: " + absolute_path) print("Directory Path: " + os.path.dirname(absolute_path))

輸出

執行上述程式後,將生成以下輸出。

Full path: c:\users\pranathi\desktop\python prog\untitled1.py
Directory Path: c:\users\pranathi\desktop\python prog

更新於: 2022-09-16

7K+ 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.