python获取当前路径

栏目: Python · 发布时间: 7年前

内容简介:总结一下python获取目录的方法在/usr/local/scripts 目录下创建一个basedir.py,具体内容如下在/usr/local/scripts/mysql 目录下执行python basedir.py,结果如下

总结一下 python 获取目录的方法

在/usr/local/scripts 目录下创建一个basedir.py,具体内容如下

# -*- encoding=utf-8 -*-

import os, sys 

print("__file__ = %s" % __file__) 
print("os.path.realpath(__file__) = %s" % os.path.realpath(__file__))
print("os.path.dirname(os.path.realpath(__file__)) = %s" % os.path.dirname(os.path.realpath(__file__)))
print("os.path.split(os.path.realpath(__file__)) = %s" % os.path.split(os.path.realpath(__file__))[0])
print("os.path.abspath(__file__) = %s" % os.path.abspath(__file__))
print("os.path[0] = %s" % sys.path[0])
print("os.getcwd() = %s" % os.getcwd())
print("sys.argv[0] = %s" % sys.argv[0])

在/usr/local/scripts/mysql 目录下执行python basedir.py,结果如下

__file__ = basedir.py
os.path.realpath(__file__) = /usr/local/scripts/mysql/basedir.py
os.path.dirname(os.path.realpath(__file__)) = /usr/local/scripts/mysql
os.path.split(os.path.realpath(__file__)) = /usr/local/scripts/mysql
os.path.abspath(__file__) = /usr/local/scripts/mysql/basedir.py
os.path[0] = /usr/local/scripts/mysql
os.getcwd() = /usr/local/scripts/mysql
sys.argv[0] = basedir.py

在root目录下执行python /usr/local/scripts/mysql/basedir.py,结果如下

__file__ = /usr/local/scripts/mysql/basedir.py
os.path.realpath(__file__) = /usr/local/scripts/mysql/basedir.py
os.path.dirname(os.path.realpath(__file__)) = /usr/local/scripts/mysql
os.path.split(os.path.realpath(__file__)) = /usr/local/scripts/mysql
os.path.abspath(__file__) = /usr/local/scripts/mysql/basedir.py
os.path[0] = /usr/local/scripts/mysql
os.getcwd() = /root
sys.argv[0] = /usr/local/scripts/mysql/basedir.py

os.path[0] 获得的是脚本文件的所在目录

os.getcwd() 获得的是执行脚本时是在的目录


以上所述就是小编给大家介绍的《python获取当前路径》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Dive Into Python 3

Dive Into Python 3

Mark Pilgrim / Apress / 2009-11-6 / USD 44.99

Mark Pilgrim's Dive Into Python 3 is a hands-on guide to Python 3 (the latest version of the Python language) and its differences from Python 2. As in the original book, Dive Into Python, each chapter......一起来看看 《Dive Into Python 3》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码