python之获取路径

xiaoxiao2021-02-28  98

在程序中需要用当当前文件的目录,用于别的操作,比如:寻找log、config等对应的目录

一、在程序启动加上命令参数,程序中获取。

python test.py  /apphome/mypy/test

在程序中,就可以获取了

mydir=sys.argv[2]

二、同os.path的方法获取

basedir=os.path.absptah(os.path.dirname(__file__))

1、os.path.dirname(__file__)

当运行python程序是绝对路径是,返回绝对路径     python /apphome/mypy/test/1.py     >>> 运行结果     /apphome/mypy/test

当运行python程序是在当前相对路径,返回空         python 1.py   >>> 运行结果 为空

2、os.path.abspath

这个主要是对于上去的第二种情况进行容错错误。 当os.path.dirname为空后返回当前路径 

>>> import os    >>> print os.path.abspath("")

/apphome/mypy/test

比如上面第二种情况,就会返回  /apphome/mypy/test

os.path.abspath("1.py")  >>> 运行结果  /apphome/mypy/test/1.py


转载请注明原文地址: https://www.6miu.com/read-43503.html

最新回复(0)