>>>import os.path##加载os.path包
>>>os.path.split('/TJ/Project/chenggm/test.py')#拆分路径,返回目录和文件名构成的元组
('/TJ/Projext/chenggm', 'test.py')
>>>os.path.dirname('/TJ/Project/chenggm/test.py')#返回文件所在的目录
'/TJ/Project/chenggm'
>>>os.path.basename('/TJ/Project/chenggm/test.py')#返回文件名字
>>> os.path.join('/TJ/Project','chenggm', 'test.py')#生成文件路径
'/TJ/Project/chenggm/test.py'
>>>os.path.abspath('./test.py')#获取文件的绝对路径
'/TJ/Project/chenggm/test.py'
>>> os.path.exists('./test.py')#判断文件是否存在
True
>>> os.path.exists('./')
True
>>> os.path.getsize('./test.py')#判断文件是否是空。getsize函数返回以字节为单位的文件大小
297
>>> os.path.isfile('./test.py')#判断是否是文件
True
>>> os.path.isdir('./')#判断是否是路径
True
###创建删除目录通过os模块进行,mkdir函数创建单个目录,makedirs函数递归创建目录,用法如下
>>> import os
>>> os.mkdir('test')
# 当已经存在时,会报错
>>> os.mkdir('test')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: 'test'
>>> os.makedirs('test/test')
#remove函数删除文件,rmdir函数删除目录,用法如下
>>> os.remove('test.py')
>>> os.rmdir('./test/test')
#列出文件夹下的所有文件和目录
>>> os.listdir('./')
['test.py', 'test1.py']
网友评论