前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python模块知识8:configparser、压缩模块

Python模块知识8:configparser、压缩模块

作者头像
企鹅号小编
发布2018-01-11 17:22:11
5990
发布2018-01-11 17:22:11
举报
文章被收录于专栏:编程编程

一、configparser模块

configparser用于处理特定格式的文件,其本质上是利用open来操作文件。

文件格式如:

1.基本的读取配置文件

-read(filename) 直接读取ini文件内容

-sections() 得到所有的section,并以列表的形式返回

-options(section) 得到该section的所有option

-items(section) 得到该section的所有键值对

-get(section,option) 得到section中option的值,返回为string类型

-getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。

2.基本的写入配置文件

-add_section(section) 添加一个新的section

-set( section, option, value) 对section中的option进行设置,需要调用write将内容写入配置文件。

案例1:取节点、键值对、键、键下面的值

importconfigparser#导入模块

config=configparser.ConfigParser()#必须的装载语句

config.read('black.txt',encoding='utf-8')#从文件中读取内容

ret=config.sections()#取所有的节点

ret2=config.items("sec1")#取节点值1下的所有的键值对

ret3=config.options('sec1')#获取节点值1下的所有的键

ret4=config.get('sec1',"k1")#获取节点值1,k1键下的值

print(ret)#执行结果['sec1', 'sec2', 'sec3']

print(ret2)#执行结果[('k1', 'v1 # 值'), ('k2', 'v2 # 值')]

print(ret3)#执行结果['k1', 'k2']

print(ret4)#执行结果v1 # 值

执行结果:

案例2:操作节点

#添加节点、键值对

importconfigparser#导入模块

config=configparser.ConfigParser()#必须的装载语句

config.add_section("sec4")#添加节点

config.set("sec4","k2","jjj")#添加节点下的键值对

config.write(open('black.txt','a'))

执行结果:

案例3:检查节点

#检查节点是否存在

importconfigparser#导入模块

config=configparser.ConfigParser()#必须的装载语句

config.read('black.txt',encoding='utf-8')#从文件中读取内容

#检查是否有某个节点

has_sec=config.has_section("sec2")#检查是否有节点“sec2”

print(has_sec)

执行结果:TRUE

案例4:删除节点

#删除节点或者节点下的键值对

importconfigparser#导入模块

config=configparser.ConfigParser()#必须的装载语句

config.read('black.txt',encoding='utf-8')#从文件中读取内容

config.remove_section('sec3')#删除节点

# config.remove_option('sec3','k1')#删除节点

config.write(open('black.txt','w'))

二、压缩zipfile模块

1)压缩

import zipfile

z=zipfile.ZipFile('a.zip','w')

z.write('hh.xml')

z.write('hhnew3')

z.close()

2)解压缩

import zipfile

z=zipfile.ZipFile('a.zip','r')

z.extractall()#解压全部

for item in z.namelist():

print(item,type(item))

z.close()

三、tar文件夹解压

1)压缩

import tarfile

tar = tarfile.open('your.tar','w')#压缩tar文件

tar.add('hh.xml', arcname='hh1.xml')#可以把hh压缩时改名为hh1

tar.add('hhnew3', arcname='hh3')

tar.close()

2)解压

tar = tarfile.open('your.tar','r')

#tar.extractall() # 可设置解压所有的问题

#打印所有的对象

for item in tar.getmembers():

print(item,type(item))

#单个解压缩文件

obj=tar.getmember("hh1.xml")

tar.extract(obj)

tar.close()

本文来自企鹅号 - 乐想屋媒体

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文来自企鹅号 - 乐想屋媒体

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
数据库
云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档