python中获取文件目录的方法

时间:2022-08-23 12:07:01

获取文件路径引用的模块可以有:sys/os

用sys.args[0]参数是获得主执行文件路径的最佳方法;

也可以调用__file__这个参数,但是"__file__" 是用来获得模块所在的路径的;具体如下:

 1 #!/usr/bin/env python
2 # coding: utf-8
3
4 import sys
5 import os
6
7 jms_dir = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
8 print "sys.argv[0]获取主执行文件路径的最佳方法,它可能是一个相对路径 ---------->>>> ",sys.argv[0]
9 print "__file__ 是用来获得模块所在的路径的,这可能得到的是一个相对路径 ---------->>>> ",__file__
10 print "os.path.dirname(__file__)获取__file__的相对目录 ---------->>>> " ,os.path.dirname(__file__)
11 print "os.path.abspath(__file__)表示获取__file__模块的绝对路径 ---------->>>> ",os.path.abspath(__file__)
12 print "os.path.abspath(sys.argv[0])表示获取的绝对路径 ---------->>>> ",os.path.abspath(sys.argv[0])
13 print "os.path.dirname(os.path.abspath(os.path.dirname(__file__))) ---------->>>> ",jms_dir
14 print "os.path.abspath(os.path.dirname(__file__)) ---------->>>> ",os.path.abspath(os.path.dirname(__file__))
15 print "os.path.dirname(os.path.abspath(__file__)) ---------->>>> " ,os.path.dirname(os.path.abspath(__file__))
结果为:
1 [root@localhost hejoy]# ./q.py 
2 sys.argv[0]获取主执行文件路径的最佳方法,它可能是一个相对路径 ---------->>>> ./q.py
3 __file__ 是用来获得模块所在的路径的,这可能得到的是一个相对路径 ---------->>>> ./q.py
4 os.path.dirname(__file__)获取__file__的相对目录 ---------->>>> .
5 os.path.abspath(__file__)表示获取__file__模块的绝对路径 ---------->>>> /home/hejoy/q.py
6 os.path.abspath(sys.argv[0])表示获取的绝对路径 ---------->>>> /home/hejoy/q.py
7 os.path.dirname(os.path.abspath(os.path.dirname(__file__))) ---------->>>> /home
8 os.path.abspath(os.path.dirname(__file__)) ---------->>>> /home/hejoy
9 os.path.dirname(os.path.abspath(__file__)) ---------->>>> /home/hejoy