如何在Python中獲取當前檔案目錄的完整路徑?
Python的OS模組包含用於建立和刪除目錄(資料夾)、檢索其內容、更改和識別當前目錄以及更多功能的函式。要與底層作業系統互動,必須首先匯入os模組。
可以在Python中獲取正在執行的程式程式碼的位置(路徑)。使用`__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
廣告