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