Python 系統路徑小結

文件夾路徑:F:\003 SVN_DEV\project\Spiders
包含文件:F:\003 SVN_DEV\project\Spiders\test.pyF:\003 SVN_DEV\project\Spiders\test_headers.txt

# test.py
import os

file_name = 'test_headers.txt'
# 獲取當前運行文件同目錄下的其他文件的絕對路徑
file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), file_name) 

# 打印當前文件的路徑
print(__file__)

# 打印當前文件運行目錄
print(os.getcwd())

# 打印當前文件的絕對路徑
print(os.path.abspath(__file__))

# 打印當前文件的目錄路徑
print(os.path.dirname(os.path.abspath(__file__)))

# 打印當前文件的文件名
print(os.path.basename(os.path.abspath(__file__)))

# 打印同一目錄下的其他文件的絕對路徑
print(os.path.join(os.path.dirname(os.path.abspath(__file__)), file_name))

# 使用當前文件的目錄與當前文件的文件名進行拼接,等同於當前文件的絕對路徑
print(os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.basename(os.path.abspath(__file__))))

運行

F:\003 SVN_DEV\project\Spiders> python "f:/003 SVN_DEV/project/Spiders/test.py"

輸出如下

f:/003 SVN_DEV/project/Spiders/test.py
F:\003 SVN_DEV\project\Spiders
f:\003 SVN_DEV\project\Spiders\test.py
f:\003 SVN_DEV\project\Spiders
test.py
f:\003 SVN_DEV\project\Spiders\test_headers.txt
f:\003 SVN_DEV\project\Spiders\test.py
F:\003 SVN_DEV\project\Spiders

切換運行目錄

F:\003 SVN_DEV\project\> python "f:/003 SVN_DEV/project/Spiders/test.py"

只給出 print(os.getcwd()) 這一條的輸出,輸出如下

F:\003 SVN_DEV\project
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章