Python: 如何獲取當前的工作目錄? os.getcwd() ; os.path.dirname( os.path.abspath( __file__ ))

加入好友
加入社群
Python: 如何獲取當前的工作目錄? os.getcwd() ; os.path.dirname( os.path.abspath( __file__ )) - 儲蓄保險王

import os

current_dir = os.path.dirname(os.path.abspath(__file__))
print("current_dir:",current_dir)
print("abspath:",os.path.abspath(__file__))
print("__file__:",__file__)

Python: 如何獲取當前的工作目錄? os.getcwd() ; os.path.dirname( os.path.abspath( __file__ )) - 儲蓄保險王

os.path.abspath(__file__)

用于获取当前脚本的绝对路径,

os.path.dirname()

用于获取文件所在文件夹的路径。

这个代码将打印出当前.py文件

所在的文件夹路径。

就Spyder輸出結果來看,

不需要os.path.abspath()

__file__ 已經是指定到py檔的絕對路徑

 

在Spyder的IPython控制台中運行代碼時,

__file__變量確實已被定義,

並且包含當前運行的Python腳本的絕對路徑。

因此,直接使用__file__變量

即可獲取當前腳本的絕對路徑。

而在某些情況下,

如果你的腳本是在其他地方引用的,

那麼使用os.path.abspath()

可以確保始終獲取腳本的絕對路徑。

 

current_dir = os.getcwd() :

Python: 如何獲取當前的工作目錄? os.getcwd() ; os.path.dirname( os.path.abspath( __file__ )) - 儲蓄保險王

“cwd” 是 “current working directory” 的縮寫,

指的是當前工作目錄。

 

在文件路径中使用”./”表示当前目录。

例如,如果你当前的工作目录是”/home/user”,

那么”./file.txt”将指向”/home/user/file.txt”。

Python: 如何獲取當前的工作目錄? os.getcwd() ; os.path.dirname( os.path.abspath( __file__ )) - 儲蓄保險王

推薦hahow線上學習python: https://igrape.net/30afN

 

加入好友
加入社群
Python: 如何獲取當前的工作目錄? os.getcwd() ; os.path.dirname( os.path.abspath( __file__ )) - 儲蓄保險王

儲蓄保險王

儲蓄險是板主最喜愛的儲蓄工具,最喜愛的投資理財工具則是ETF,最喜愛的省錢工具則是信用卡

You may also like...

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *