天天看點

Python中os.path的妙用

1.基本知識

    os.path在不同的環境中設定檔案的路徑時作用非常大,我們經常在Django或Flask中都看到它的身影,常用的其實有下面的幾個方法:

常用方法

作用

os.path.dirname(__file__)

傳回目前python執行腳本的執行路徑(看下面的例子),這裡__file__為固定參數

os.path.abspath(file)

傳回一個檔案在目前環境中的絕對路徑,這裡file 一參數

os.path.join(basedir,file)

将file檔案的路徑設定為basedir所在的路徑,這裡fbasedir和file都為參數

    OK,我們不妨看下面的例子。

2.測試

    先看一下我目前環境下的兩個python腳本檔案:

1

2

3

4

<code>xpleaf@leaf:~</code><code>/Source_Code</code><code>$ </code><code>pwd</code>

<code>/home/xpleaf/Source_Code</code>

<code>xpleaf@leaf:~</code><code>/Source_Code</code><code>$ </code><code>ls</code>

<code>hello.py  test_os_path.py</code>

    hello.py裡面沒有内容,待會用來做測試,主要來看一下test_os_path.py的代碼:

5

6

7

8

9

10

11

12

13

<code>import</code> <code>os</code>

<code>path1 </code><code>=</code> <code>os.path.dirname(__file__)</code>

<code>print</code> <code>'The path1 is:'</code><code>, path1</code>

<code>path2 </code><code>=</code> <code>os.path.abspath(path1)</code>

<code>print</code> <code>'The path2 is:'</code><code>, path2</code>

<code>path3 </code><code>=</code> <code>os.path.join(path2, </code><code>'hello.py'</code><code>)</code>

<code>print</code> <code>'The path3 is:'</code><code>, path3</code>

    通過看下面的兩種執行方式,我們來深刻了解上面三個方法的作用:

(1)以相對路徑的方式來執行test_os_path.py

<code>xpleaf@leaf:~</code><code>/Source_Code</code><code>$ python test_os_path.py </code>

<code>The path1 is: </code>

<code>The path2 is: </code><code>/home/xpleaf/Source_Code</code>

<code>The path3 is: </code><code>/home/xpleaf/Source_Code/hello</code><code>.py</code>

(2)以絕對路徑的方式來執行test_os_path.py

<code>xpleaf@leaf:~</code><code>/Source_Code</code><code>$ python </code><code>/home/xpleaf/Source_Code/test_os_path</code><code>.py </code>

<code>The path1 is: </code><code>/home/xpleaf/Source_Code</code>

    通過上面兩種執行方式的輸出,就很容易看出三者的作用了。那在實際開發中,有什麼用呢?

3.在實際開發中使用os.path

    在實際開發中,我們肯定是要設定一個某些檔案的路徑的,比如在Web開發中,對于模闆和靜态檔案的路徑設定等,其實如果你用過Django或者Flask,應該就可以經常看到在它們的配置檔案中,有os.path的出現,一般這樣來用:

(1)首先獲得目前檔案(比如配置檔案)所在的路徑

<code>basedir </code><code>=</code> <code>os.path.abspath(os.path.dirname(__file__))</code>

(2)設定某個檔案的絕對路徑

<code>static_file_path </code><code>=</code> <code>os.path.join(basedir, </code><code>'index.html'</code><code>)</code>

    當然,os.path的用法還有很多還多,這裡隻是列出常用的這三種,并且給出開發環境的一般用法,至于是否非得這樣用,完全看每個人自己的思路和方法,這裡僅提供參考。

本文轉自 xpleaf 51CTO部落格,原文連結:http://blog.51cto.com/xpleaf/1736956,如需轉載請自行聯系原作者