操作键值对文件

 #文件db格式为
[section]
a = 1
b = 2 [section1]
d = 3
c = 4 import configparser #获取所有节点
config = configparser.ConfigParser()
config.read('db')
ret = config.sections()
print(ret) >>>['section', 'section1'] #获取指定节点下所有的键值对
ret = config.items('section1')
print('获取键值对:',ret)
>>>获取键值对: [('d', ''), ('c', '')] #获取所有的键
ret = config.options('section')
print('获取节点下键名称:',ret)
>>>获取节点下键名称: ['a', 'b'] #获取节点下的指定key的值
ret =config.get('section1','c')
print(ret)
>>>4 #检查节点是否存在
has_sec = config.has_section('section1')
print(has_sec)
>>>True #添加节点section2
config.add_section('section2')
config.write(open('db','w')) #db文件当前为
[section]
a = 1
b = 2 [section1]
d = 3
c = 4 [section2] #删除节点section2
config.remove_section('section2')
config.write(open('db','w')) #当前db文件内容为
[section]
a = 1
b = 2 [section1]
d = 3
c = 4 #检查删除设置指定组内的键值对是否存在
has_opt = config.has_option('section1','c')
print(has_opt)
>>>True #删除
config.remove_option('section1','c')
config.write(open('db','w'))
#当前db文件内容为
[section]
a = 1
b = 2 [section1]
d = 3 #设置更改指定值
config.set('section1','d','')
config.write(open('db','w'))
#db内容
[section]
a = 1
b = 2 [section1]
d = 123
c = 4
 #oo.xml文件内容
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2023</year>
<year>2027</year>
<year>2027</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Austria" />
<neighbor direction="W" name="Switzerland" />
</country>
</data> from xml.etree import ElementTree as ET #打开xml文件加载到内存
tree = ET.parse('oo.xml')
#获取根节点
root = tree.getroot() for child in root:
print(child.tag,child.attrib)#child.tag,子节点标签名,子节点属性
for gradechild in child:
print(gradechild.tag,gradechild.text,gradechild.attrib) >>>country {'name': 'Liechtenstein'}
>>>rank 2 {'updated': 'yes'}
>>>year 2023 {}
>>>gdppc 141100 {}
>>>neighbor None {'direction': 'E', 'name': 'Austria'}
>>>neighbor None {'direction': 'W', 'name': 'Switzerland'} #两种方法读取xml文件直接解析,tree对象是ElementTree对象
tree = ET.parse('oo.xml')
root = tree.getroot() #将xml已字符串格式获得,将字符串转化为element对象,无法进行写操作
str_xml = open('oo.xml','r').read()
root = ET.XML(str_xml) #循环所有的year节点
for node in root.iter('year'):
#将year节点中的内容自增一
new_year = int (node.text) +1
node.text = str(new_year)
print(node.text)
>>>2024
>>>2027
>>>2027
#设置属性
node.set('name','alex')
node.set('age','')
print(node.attrib)
>>>{'age': '', 'name': 'alex'}
>>>{'age': '', 'name': 'alex'}
>>>{'age': '', 'name': 'alex'}
#删除属性
del node.attrib['name']
print(node.attrib)
>>>{'age': ''}
>>>{'age': ''}
>>>{'age': ''}
#保存文件
tree = ET.ElementTree(root)
tree.write("newnew.xml", encoding='utf-8')
 #创建根节点
root = ET.Element('family') #创建大儿子
son1 = ET.Element('son',{'name':'儿子1'})
#创建二儿子
son2 = ET.Element('son',{'name':'儿子2'}) #大儿子中创建两个孙子
grandson1 = ET.Element('grandson',{'name':'孙子1'})
grandson2 = ET.Element('grandson',{'name':'孙子2'})
son1.append(grandson1)
son2.append(grandson2) root.append(son1)
root.append(son2) tree = ET.ElementTree(root)
tree.write('ooo.xml',encoding = 'utf-8',short_empty_elements = False)
#ooo.xml文件为
<family><son name="儿子1"><grandson name="孙子1"></grandson></son><son name="儿子2"><grandson name="孙子2"></grandson></son></family>

python-configparser模块,xml.etree模块的更多相关文章

  1. python标准库xml.etree.ElementTree的bug

    使用python生成或者解析xml的方法用的最多的可能就数python标准库xml.etree.ElementTree和lxml了,在某些环境下使用xml.etree.ElementTree更方便一些 ...

  2. [python 学习] 使用 xml.etree.ElementTree 模块处理 XML

    ---恢复内容开始--- 导入数据(读文件和读字符串) 本地文件 country_data.xml <?xml version="1.0"?> <data> ...

  3. Python全栈之路----常用模块----xml处理模块

    xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业的很多系统的 ...

  4. Python3使用xml.dom.minidom和xml.etree模块儿解析xml文件,封装函数

    总结了一下使用Python对xml文件的解析,用到的模块儿如下: 分别从xml字符串和xml文件转换为xml对象,然后解析xml内容,查询指定信息字段. from xml.dom.minidom im ...

  5. json,pickle,shelve模块,xml处理模块

    常用模块学习—序列化模块详解 什么叫序列化? 序列化是指把内存里的数据类型转变成字符串,以使其能存储到硬盘或通过网络传输到远程,因为硬盘或网络传输时只能接受bytes. 为什么要序列化? 你打游戏过程 ...

  6. [python 2.x] xml.etree.ElementTree module

    XML 文件:xmlparse.xml <?xml version="1.0" encoding="UTF-8" standalone="no& ...

  7. python ConfigParser、shutil、subprocess、ElementTree模块简解

    ConfigParser 模块 一.ConfigParser简介ConfigParser 是用来读取配置文件的包.配置文件的格式如下:中括号“[ ]”内包含的为section.section 下面为类 ...

  8. python基础——15(加密、excel操作、ini文件操作、xml操作模块及数据格式分类)

    一.加密模块 1.有解密的加密方式(base64) #base64加密 import base64 str_encrypt = input("输入要加密的字符串:\n") base ...

  9. [python标准库]XML模块

    1.什么是XML XML是可扩展标记语言(Extensible Markup Language)的缩写,其中的 标记(markup)是关键部分.您可以创建内容,然后使用限定标记标记它,从而使每个单词. ...

随机推荐

  1. C. Tanya and Toys_模拟

    C. Tanya and Toys time limit per test 1 second memory limit per test 256 megabytes input standard in ...

  2. ios 创建自己的.a文件

    1:首先创建个 静态工程(Cocoa Touch Static Library); 方法名字,一定要暴露在.h文件中, 2:分别在模拟器环境和真机环境下 Analyze (shift+command+ ...

  3. React的安装

    创建: 2019/05/01 完成: 2019/05/01 create-react-app  学习及创建单页app npx create-react-app my-app cd my-app npm ...

  4. Eclipse Python插件 PyDev

    PyDev for Eclipse 是一个功能强大且易用的 Eclipse Python IDE 插件.本文将向读者介绍 PyDev 开源项目及其安装配置方法,并在此基础上详细介绍如何利用 PyDev ...

  5. DTcms网站伪静态逻辑

    我们之前写伪静态就是web.config里面配置好.-->配置伪静态(URL重写),DTcms网站写的伪静态跟之前的不一样,他是静态页面和代码现实了分离.http://demo.dtcms.ne ...

  6. C# if语句

    一.C# if语句 if语句根据条件判断代码该执行哪一个分支. if语句有两个或两个以上的分支供代码选择,但是每次只能执行一个分支. 1. 基本if语句 语法格式如下: if(expression){ ...

  7. 开源项目托管github步骤

    一.在github新建项目,复制到本地更改之后命令提交. 1.进入github主页新建项目:https://github.com/ccyinghua 2.复制项目地址 3.打开git Bash 命令行 ...

  8. Server_Tomcat

    1 Tomcat概述 Tomcat服务器由Apache提供,开源免费.由于Sun和其他公司参与到了Tomcat的开发中,所以最新的JSP/Servlet规范总是能在Tomcat中体现出来.当前最新版本 ...

  9. 关于 export default 和 export

    // 第一组 export default function crc32() { // 输出 // ... } import crc32 from 'crc32'; // 输入 // 第二组 expo ...

  10. 高封装的property方法

    class Person(): def __init__(self): self.__age = 0 def set_age(self, age): if age < 0 or age > ...