码迷,mamicode.com
首页 > 编程语言 > 详细

python中获取文件目录的方法

时间:2017-08-11 11:03:15      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:引用   path   env   文件   localhost   color   local   python   jms   

获取文件路径引用的模块可以有: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

 

 

python中获取文件目录的方法

标签:引用   path   env   文件   localhost   color   local   python   jms   

原文地址:http://www.cnblogs.com/st12345/p/7344238.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!