os.path的一些常用方法

os.path模块主要用于文件的属性获取,在编程中经常用到,以下是该模块的几种常用方法。

官方文档:http://docs.python.org/library/os.path.html

1. os.path.abspath(path)

返回path规范化的绝对路径。

import os.path

In[2]: os.path.abspath("logo3.png")
Out[2]: 'C:\\Users\\hong\\Desktop\\logo3.png'
2. os.path.split(path)

返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素。

In[2]: os.path.split("C:\\Users\\hong\\Desktop\\logo3.png")
Out[4]: ('C:\\Users\\hong\\Desktop', 'logo3.png')
3. os.path.exists(path)

如果path存在,返回True;如果path不存在,返回False。

In[2]: os.path.exists('c:\\')
Out[5]: True

In[2]: os.path.exists('logo3.png')
Out[6]: True
os.path.isabs(path)
os.path.isfile(path)
>>> os.path.isfile('c:\\boot.ini')   
True   

猜你喜欢

转载自www.cnblogs.com/datanewblood/p/9298677.html