Python模块:os

扫码查看

OS模块常用用法:

os.name()   #判断当前使用的系统环境,windows则返回 ‘nt’,Linux则返回‘posix’
os.getcwd() #显示当前目录
os.listdir() #以列表的形式显示当前目录下的所有文件名和目录名,但不会区分文件和目录。
os.remove() #删除指定文件
os.rmdir() #删除指定目录
os.mkdir() #创建一层目录
os.mkdirs() #创建多层目录
os.system() #执行shell命令
os.chdir() #切换目录
os.walk() #遍历目录下所有内容,产生三元组 (dirpath, dirnames, filenames)【文件夹路径, 文件夹名字, 文件名】

os.path模块:

os.path.isfile()   #判定对象是否是文件,是则返回True,否则返回False
os.path.isdir() #判定对象是否是目录,是则返回True,否则返回False
os.path.exists() #判定对象是否存在,是则返回True,否则返回False
os.path.split() #分割路径和文件名
>>> os.path.split('D:\SWbackup\list.txt')
('D:\\SWbackup', 'list.txt') os.path.getsize() #获取文件大小,如果为目录则返回0
os.path.abspath() #获取绝对路径
>>> os.path.abspath('.')
'C:\\Python33' os.path.join(path,name) #连接目录和文件名
os.path.basename(path) #返回文件名
os.path.dirname(path) #返回文件路径

例:#遍历D:\SWbackup目录下所有目录,并打印出其绝对路径

import os
for path,d,filelist in os.walk('D:\SWbackup'):
for filename in filelist:
filepath = os.path.join(path,filename)
print(filepath)

输出结果:

D:\SWbackup\cisco.vbs
D:\SWbackup\h3c.vbs
D:\SWbackup\list.txt
D:\SWbackup\list2.txt
D:\SWbackup\log\20160331\1.1.1.1.txt
D:\SWbackup\log\20160331\10.10.7.250.txt
D:\SWbackup\log\20160331\10.10.7.251.txt
D:\SWbackup\log\20160331\10.10.7.252.txt
D:\SWbackup\log\20160331\10.10.7.254.txt
05-02 15:27
查看更多