99热99这里只有精品6国产,亚洲中文字幕在线天天更新,在线观看亚洲精品国产福利片 ,久久久久综合网

歡迎加入QQ討論群258996829
麥子學院 頭像
蘋果6袋
6
麥子學院

Python 獲取當前路徑的方法

發(fā)布時間:2017-08-05 20:16  回復:0  查看:2904   最后回復:2017-08-05 20:16  
本文和大家分享的主要是python 獲取當前路勁相關內容,一起來看看吧,希望對大家 學習python有所幫助。
  sys.path
  模塊搜索路徑的字符串列表。由環(huán)境變量PYTHONPATH 初始化得到。
  sys.path[0] 是調用 Python 解釋器的當前腳本所在的目錄。
  sys.argv
  一個傳給Python 腳本的指令參數列表。
  sys.argv[0] 是腳本的名字(由系統(tǒng)決定是否是全名)
  假設顯示調用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  ,會得到相對路徑。
  為了獲取絕對路徑,可調用 os.path.abspath()
  os.path  中的一些方法
  os.path.split(path)
  將路徑名稱分成頭和尾一對。尾部永遠不會帶有斜杠。如果輸入的路徑以斜杠結尾,那么得到的空的尾部。
  如果輸入路徑沒有斜杠,那么頭部位為空。如果輸入路徑為空,那么得到的頭和尾都是空。
  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:\


來源:RustFisher

您還未登錄,請先登錄

熱門帖子

最新帖子

?