引言
在編寫 Python 程序時,我們經常需要處理文件,此時獲取當前文件所在路徑十分重要。在本篇文章中,我們將探討如何使用 Python 獲取當前文件路徑。
獲取當前文件路徑的方法
方法一:使用 os 模塊
Python 的 os 模塊提供了獲取文件路徑的方法。
import os current_path = os.path.abspath(__file__) print("當前文件路徑是:", current_path)
通過調用 os 模塊的 path.abspath()
方法獲取絕對路徑,傳入的參數是#__file__,表示當前腳本文件的絕對路徑。
可以使用 os.path.dirname()
獲取當前文件所在的目錄路徑。
import os current_path = os.path.abspath(__file__) dir_path = os.path.dirname(current_path) print("當前文件所在目錄路徑是:", dir_path)
通過調用 os 模塊的 path.dirname()
方法獲取當前文件所在目錄的路徑。
方法二:使用 pathlib 模塊
Python 3.4 引入了 pathlib 模塊,使用它可以更加簡單地獲取文件路徑。
from pathlib import Path current_path = Path(__file__).resolve() print("當前文件路徑是:", current_path)
Path 對象的 __file__
屬性返回當前腳本文件所在的路徑,再使用 Path 的 resolve()
方法獲取絕對路徑。
還可以使用 Path 的 parent
屬性獲取當前文件所在的目錄路徑。
from pathlib import Path current_path = Path(__file__).resolve() dir_path = current_path.parent print("當前文件所在目錄路徑是:", dir_path)
方法三:使用 inspect 模塊
inspect 模塊提供了獲取當前文件路徑的方法。
import inspect current_path = inspect.getfile(inspect.currentframe()) print("當前文件路徑是:", current_path)
inspect.getfile() 方法返回當前腳本文件的路徑。
不推薦使用 inspect 模塊獲取當前文件路徑,因為它有一些明顯缺陷——在某些 Python 解釋器中可能不起作用,因此,它的使用受到了限制。
總結
在本文中,我們討論了 Python 中獲取當前文件路徑的三種方法。os 模塊是最常用的方法,而 pathlib 模塊和 inspect 模塊也提供了很有用的函數。
小節:
在 Python 中,如何獲取當前文件所在路徑?
如何獲取當前文件所在目錄的路徑?
可以使用 os 模塊、pathlib 模塊和 inspect 模塊中的方法獲取當前文件路徑。
使用 os.path.dirname() 或 Path.parent 屬性可以獲取當前文件所在目錄的路徑。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/239055.html