一、shelve模块

 shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型
import shelve

f=shelve.open(r'sheve.txt')
# f['stu1_info']={'name':'egon','age':18,'hobby':['piao','smoking','drinking']}
# f['stu2_info']={'name':'gangdan','age':53}
# f['school_info']={'website':'http://www.pypy.org','city':'beijing'} print(f['stu1_info']['hobby'])
f.close()

二、xml模块

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业的很多系统的接口还主要是xml。
xml的格式如下,就是通过<>节点来区别数据结构的:
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml:
# print(root.iter('year')) #全文搜索
# print(root.find('country')) #在root的子节点找,只找一个
# print(root.findall('country')) #在root的子节点找,找所有
import xml.etree.ElementTree as ET

tree = ET.parse("xmltest.xml")
root = tree.getroot()
print(root.tag) #遍历xml文档
for child in root:
print('========>',child.tag,child.attrib,child.attrib['name'])
for i in child:
print(i.tag,i.attrib,i.text) #只遍历year 节点
for node in root.iter('year'):
print(node.tag,node.text)
#--------------------------------------- import xml.etree.ElementTree as ET tree = ET.parse("xmltest.xml")
root = tree.getroot() #修改
for node in root.iter('year'):
new_year=int(node.text)+1
node.text=str(new_year)
node.set('updated','yes')
node.set('version','1.0')
tree.write('test.xml') #删除node
for country in root.findall('country'):
rank = int(country.find('rank').text)
if rank > 50:
root.remove(country) tree.write('output.xml')
#在country内添加(append)节点year2
import xml.etree.ElementTree as ET
tree = ET.parse("a.xml")
root=tree.getroot()
for country in root.findall('country'):
for year in country.findall('year'):
if int(year.text) > 2000:
year2=ET.Element('year2')
year2.text='新年'
year2.attrib={'update':'yes'}
country.append(year2) #往country节点下添加子节点 tree.write('a.xml.swap')
自己创建xml文档:
import xml.etree.ElementTree as ET new_xml = ET.Element("namelist")
name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
age = ET.SubElement(name,"age",attrib={"checked":"no"})
sex = ET.SubElement(name,"sex")
sex.text = '33'
name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
age = ET.SubElement(name2,"age")
age.text = '19' et = ET.ElementTree(new_xml) #生成文档对象
et.write("test.xml", encoding="utf-8",xml_declaration=True) ET.dump(new_xml) #打印生成的格式

三、configparser模块

配置文件如下:

复制代码
# 注释1
; 注释2 [section1]
k1 = v1
k2:v2
user=egon
age=18
is_admin=true
salary=31 [section2]
k1 = v1
读取:
import configparser config=configparser.ConfigParser()
config.read('a.cfg') #查看所有的标题
res=config.sections() #['section1', 'section2']
print(res) #查看标题section1下所有key=value的key
options=config.options('section1')
print(options) #['k1', 'k2', 'user', 'age', 'is_admin', 'salary'] #查看标题section1下所有key=value的(key,value)格式
item_list=config.items('section1')
print(item_list) #[('k1', 'v1'), ('k2', 'v2'), ('user', 'egon'), ('age', '18'), ('is_admin', 'true'), ('salary', '31')] #查看标题section1下user的值=>字符串格式
val=config.get('section1','user')
print(val) #egon #查看标题section1下age的值=>整数格式
val1=config.getint('section1','age')
print(val1) #18 #查看标题section1下is_admin的值=>布尔值格式
val2=config.getboolean('section1','is_admin')
print(val2) #True #查看标题section1下salary的值=>浮点型格式
val3=config.getfloat('section1','salary')
print(val3) #31.0
改写:
import configparser config=configparser.ConfigParser()
config.read('a.cfg',encoding='utf-8') #删除整个标题section2
config.remove_section('section2') #删除标题section1下的某个k1和k2
config.remove_option('section1','k1')
config.remove_option('section1','k2') #判断是否存在某个标题
print(config.has_section('section1')) #判断标题section1下是否有user
print(config.has_option('section1','')) #添加一个标题
config.add_section('egon') #在标题egon下添加name=egon,age=18的配置
config.set('egon','name','egon')
config.set('egon','age',18) #报错,必须是字符串 #最后将修改的内容写入文件,完成最终的修改
config.write(open('a.cfg','w'))
import configparser

config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9'} config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
config.write(configfile) 基于上述方法添加一个ini文档

python之shelve、xml、configparser模块的更多相关文章

  1. python笔记-7(shutil/json/pickle/shelve/xml/configparser/hashlib模块)

    一.shutil模块--高级的文件.文件夹.压缩包处理模块 1.通过句柄复制内容 shutil.copyfileobj(f1,f2)对文件的复制(通过句柄fdst/fsrc复制文件内容) 源码: Le ...

  2. Python模块 shelve xml configparser hashlib

    常用模块1. shelve 一个字典对象模块 自动序列化2.xml 是一个文件格式 写配置文件或数据交换 <a name="hades">123</a>3. ...

  3. 模块 - json/pickle/shelve/xml/configparser

    序列化: 序列化是指把内存里的数据类型转变成字符串,以使其能存储到硬盘或通过网络传输到远程,因为硬盘或网络传输时只能接受bytes. 为什么要序列化: 有种办法可以直接把内存数据(eg:10个列表,3 ...

  4. Python学习笔记——基础篇【第六周】——json & pickle & shelve & xml处理模块

    json & pickle 模块(序列化) json和pickle都是序列化内存数据到文件 json和pickle的区别是: json是所有语言通用的,但是只能序列化最基本的数据类型(字符串. ...

  5. json/pickle/shelve/xml/configparser/hashlib/subprocess - 总结

    序列化:序列化指把内存里的数据类型转成字符串,以使其能存储到硬盘或通过网络传输到远程,因为硬盘或网络传输时只能接受bytes为什么要序列化:可以直接把内存数据(eg:10个列表,3个嵌套字典)存到硬盘 ...

  6. 小白的Python之路 day5 configparser模块的特点和用法

    configparser模块的特点和用法 一.概述 主要用于生成和修改常见配置文件,当前模块的名称在 python 3.x 版本中变更为 configparser.在python2.x版本中为Conf ...

  7. python模块(shelve,xml,configparser,hashlib,logging)

    1.1shelve模块 shelve 模块比pickle模块简单,只有一个open函数,返回类似字典对象,可读可写:key必须为字符串, 而值可以是python所支持的数据类型. shelve模块主要 ...

  8. 序列化与反序列化,json,pickle,xml,shelve,configparser模块

    序列化与反序列化 什么是序列化?序列化就是将内存中的数据结构转换成一种中间格式存储到硬盘或者基于网络传输.反序列化就是将硬盘中或者网络中传来的一种数据格式转换成内存中数据结构. 为什么要有? 1.可以 ...

  9. Python标准库之ConfigParser模块

    配置文件的格式 a) 配置文件中包含一个或多个 section, 每个 section 有自己的 option: b) section 用 [sect_name] 表示,每个option是一个键值对, ...

  10. python标准库:Configparser模块

    配置文件test.conf [section1] name = tank age = 28 [section2] ip = 192.168.1.1 port = 8080 示例 # -* - codi ...

随机推荐

  1. 三、Zookeeper简介

    一.简介 zookeeper 主要使用场景:分布式系统的分布式协同服务.协同工作就是通过某种方式,让着节点的信息能够同步和共享,依赖于进程间的通信.通信方式有俩种. 通过网络进行信息共享 现实工作中, ...

  2. 二、java多线程编程核心技术之(笔记)——如何停止线程?

    1.异常法 public class MyThread extends Thread { @Override public void run() { super.run(); try { for (i ...

  3. centos 7 安装MySQL 5.7.23

    centos 7 安装MySQL 5.7.23   1.  上传MySQL安装包到服务器 mysql-5.7.23-linux-glibc2.5-x86_64.tar.gz 2.  解压MySQL安装 ...

  4. js下 Day20、综合案例

    一.购物车 效果图: 功能思路分析: 1. 面向对象框架 2. 模拟数据 1.多个店铺数组套对象 2.每个店铺多个商品,数组套对象

  5. js下 Day05、DOM案例

    一.简易购物车 效果图: 功能思路分析: 功能一:数量加减 \1. 找到所有的加号按钮,循环绑定点击事件.点击加号时让对应的数量+1 (找清楚加号和数量的关系,让数量标签的内容++) \2. 找到所有 ...

  6. redis源码学习之lua执行原理

    聊聊redis执行lua原理 从一次面试场景说起   "看你简历上写的精通redis" "额,还可以啦" "那你说说redis执行lua脚本的原理&q ...

  7. NET 5 Topshelf 或者WorkerServices搭建 Windows/Linux 服务

    参考文章https://www.cnblogs.com/RainFate/p/12095793.html Topshelf Topshelf 是一个用来部署基于.NET Framework 开发的服务 ...

  8. EF Core 封装方法Expression<Func<TObject, bool>>与Func<TObject, bool>区别

    unc<TObject, bool>是委托(delegate) Expression<Func<TObject, bool>>是表达式 Expression编译后就 ...

  9. sqlserver varchar和Nvarchar区别

    sql server中的varchar和Nvarchar有什么区别?   答:varchar(n)长度为 n 个字节的可变长度且非 Unicode 的字符数据.n 必须是一个介于 1 和 8,000 ...

  10. C#中打印拼接的字符串

    实例化打印文档 //声明打印对象 PrintDocument pd = new PrintDocument(); int ilvPreviewIndex = 0; 在打印事件中设置基本属性 priva ...