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