欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python 獲取當前所在目錄的方法詳解

 更新時間:2017年08月02日 08:51:30   作者:RustFisher  
本文給大家講解的是使用python獲取當前所在目錄的方法以及相關(guān)示例,非常的清晰簡單,有需要的小伙伴可以參考下

sys.path

模塊搜索路徑的字符串列表。由環(huán)境變量PYTHONPATH初始化得到。

sys.path[0]是調(diào)用Python解釋器的當前腳本所在的目錄。

sys.argv

一個傳給Python腳本的指令參數(shù)列表。

sys.argv[0]是腳本的名字(由系統(tǒng)決定是否是全名)

假設(shè)顯示調(diào)用python指令,如 python demo.py ,會得到絕對路徑;

若直接執(zhí)行腳本,如 ./demo.py ,會得到相對路徑。

os.getcwd()

獲取當前工作路徑。在這里是絕對路徑。
https://docs.python.org/2/library/os.html#os.getcwd

__file__

獲得模塊所在的路徑,可能得到相對路徑。

如果顯示執(zhí)行Python,會得到絕對路徑。

若按相對路徑來直接執(zhí)行腳本 ./pyws/path_demo.py ,會得到相對路徑。

為了獲取絕對路徑,可調(diào)用 os.path.abspath()

os.path 中的一些方法

os.path.split(path)

將路徑名稱分成頭和尾一對。尾部永遠不會帶有斜杠。如果輸入的路徑以斜杠結(jié)尾,那么得到的空的尾部。

如果輸入路徑?jīng)]有斜杠,那么頭部位為空。如果輸入路徑為空,那么得到的頭和尾都是空。
https://docs.python.org/2/library/os.path.html#os.path.split

os.path.realpath(path)

返回特定文件名的絕對路徑。

https://docs.python.org/2/library/os.path.html#os.path.realpath

代碼示例

環(huán)境 Win7, Python2.7

以 /e/pyws/path_demo.py 為例

#!/usr/bin/env python
import os
import sys

if __name__ == '__main__':
  print "sys.path[0] =", sys.path[0]
  print "sys.argv[0] =", sys.argv[0]
  print "__file__ =", __file__
  print "os.path.abspath(__file__) =", os.path.abspath(__file__)
  print "os.path.realpath(__file__) = ", os.path.realpath(__file__)
  print "os.path.dirname(os.path.realpath(__file__)) =", os.path.dirname(os.path.realpath(__file__))
  print "os.path.split(os.path.realpath(__file__)) =", os.path.split(os.path.realpath(__file__))
  print "os.getcwd() =", os.getcwd()



在 /d 中運行,輸出為

$ python /e/pyws/path_demo.py
sys.path[0] = E:\pyws
sys.argv[0] = E:/pyws/path_demo.py
__file__ = E:/pyws/path_demo.py
os.path.abspath(__file__) = E:\pyws\path_demo.py
os.path.realpath(__file__) = E:\pyws\path_demo.py
os.path.dirname(os.path.realpath(__file__)) = E:\pyws
os.path.split(os.path.realpath(__file__)) = ('E:\\pyws', 'path_demo.py')
os.getcwd() = D:\



在e盤中用命令行直接執(zhí)行腳本

$ ./pyws/path_demo.py
sys.path[0] = E:\pyws
sys.argv[0] = ./pyws/path_demo.py
__file__ = ./pyws/path_demo.py
os.path.abspath(__file__) = E:\pyws\path_demo.py
os.path.realpath(__file__) = E:\pyws\path_demo.py
os.path.dirname(os.path.realpath(__file__)) = E:\pyws
os.path.split(os.path.realpath(__file__)) = ('E:\\pyws', 'path_demo.py')
os.getcwd() = E:\

相關(guān)文章

最新評論