os.path 模組中有幾個好用的api來取得當前檔案路徑,使得程式可以用更彈性方式去使用(避免了固定路徑)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import os # 當前檔案的完整名稱路徑為 D:\test\test.py # 絕對路徑 print(os.path.abspath(__file__)) # D:\test\test.py # 檔案名稱 print(os.path.basename(__file__)) # test.py # 上層路徑名稱 print(os.path.dirname(__file__)) # D:\test # 檔名與副檔名 print(os.path.splitext(os.path.basename(__file__))) # ('test', '.py') # 承上,分別獲取並設置變數 file_name, file_ext = os.path.splitext(os.path.basename(__file__)) print(f"{file_name = }, {file_ext = }") # file_name = 'test', file_ext = '.py' |