About os.path
http://blog.51cto.com/xpleaf/1736956
http://blog.csdn.net/u011760056/article/details/46969883
?
?1. Notes.
os.path.dirname(__file__)返回腳本的路徑,但是需要注意一下幾點:
1、必須是實際存在的.py文件,如果在命令行執行,則會引發異常NameError: name '__file__' is not defined
2、在運行的時候如果輸入完整的執行的路徑,則返回.py文件的全路徑如:
python c:/test/test.py 則返回路徑 c:/test ,如果是python test.py 則返回空
3、結合os.path.abspath用,效果會好,如果大家看過一些python架構的代碼的話,會發現經常有這樣的組合
os.path.dirname(os.path.abspath(__file__)),os.path.abspath(__file__)返回的是.py文件的絕對路徑
這就是os.path.dirname(__file__)的用法,其主要總結起來有:
???-- 不要以命令行的形式來進行os.path.dirname(__file__)這種形式來使用這個函數
???-- 結合os.path.abspath()使用
?
2.測試
????先看一下我當前環境下的兩個python腳本文件:
| 1 2 3 4 | xpleaf@leaf:~/Source_Code$?pwd /home/xpleaf/Source_Code xpleaf@leaf:~/Source_Code$?ls hello.py??test_os_path.py |
????hello.py里面沒有內容,待會用來做測試,主要來看一下test_os_path.py的代碼:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 | import?os path1?=?os.path.dirname(__file__) print?'The?path1?is:',?path1 path2?=?os.path.abspath(path1) print?'The?path2?is:',?path2 path3?=?os.path.join(path2,?'hello.py') print?'The?path3?is:',?path3 |
????通過看下面的兩種執行方式,我們來深刻理解上面三個方法的作用:
(1)以相對路徑的方式來執行test_os_path.py
| 1 2 3 4 | xpleaf@leaf:~/Source_Code$?python?test_os_path.py? The?path1?is:? The?path2?is:?/home/xpleaf/Source_Code The?path3?is:?/home/xpleaf/Source_Code/hello.py |
(2)以絕對路徑的方式來執行test_os_path.py
| 1 2 3 4 | xpleaf@leaf:~/Source_Code$?python?/home/xpleaf/Source_Code/test_os_path.py? The?path1?is:?/home/xpleaf/Source_Code The?path2?is:?/home/xpleaf/Source_Code The?path3?is:?/home/xpleaf/Source_Code/hello.py |
????通過上面兩種執行方式的輸出,就很容易看出三者的作用了。那在實際開發中,有什么用呢?
?
?
3.在實際開發中使用os.path
????在實際開發中,我們肯定是要設定一個某些文件的路徑的,比如在Web開發中,對于模板和靜態文件的路徑設定等,其實如果你用過Django或者Flask,應該就可以經常看到在它們的配置文件中,有os.path的出現,一般這樣來用:
(1)首先獲得當前文件(比如配置文件)所在的路徑
| 1 | basedir?=?os.path.abspath(os.path.dirname(__file__)) |
(2)設定某個文件的絕對路徑
| 1 | static_file_path?=?os.path.join(basedir,?'index.html') |
轉載于:https://www.cnblogs.com/morganh/p/8194179.html
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的About os.path的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 保存对工作的初心
- 下一篇: !假如人类使用 16 进制