天天看点

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的用法还有很多还多,这里只是列出常用的这三种,并且给出开发环境的一般用法,至于是否非得这样用,完全看每个人自己的思路和方法,这里仅提供参考。