os.path学习笔记
1.os.path.dirname(os.path.abspath(__file__)) 用法
os.path.abspath(__file__) 返回脚本的绝对路径
os.path.dirname(__file__)返回脚本的路径
通常结合起来使用,会返回当前脚本的目录
例如:
import os
fileDir = os.path.abspath(__file__)
curDir = os.path.dirname(fileDir)
print "abspath输出绝对路径包括文件名:" + fileDir
print "dirname输出路径:" + curDir
输出结果为:
abspath输出绝对路径包括文件名:c:\Users\Admin\Desktop\test.py
dirname输出路径:c:\Users\Admin\Desktop
2.os.path.split(path)
将path分割成目录和文件名二元组返回
>>> os.path.split(__file__)
('c:\\Users\\Admin\\Desktop', 'test.py')
3.os.path.basename(path)
返回path最后的文件名
>>> os.path.basename(__file__)
test.py
4.os.path.exists(path)
判断 路径/文件 是否存在
如果path存在,返回True;如果path不存在,返回False;
5.os.path.isfile(path):
只判断文件是否存在
如果path存在,返回True;如果path不存在,返回False;
ps:
__file__ 代表当前脚本的绝对路径