xml
import xml.etree.cElementTree as ET
· xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单。
· xml是通过<>节点来区别数据结构。
· xml协议在各个语言里的都是支持的。
范例1:
#!/usr/bin/env python # -*- coding: utf-8 -*- import xml.etree.cElementTree as ET tree = ET.parse("xmltest.xml") root = tree.getroot() print(root) print(root.tag, "\n") # 遍历xml文档 for child in root: print("\n", child.tag, child.attrib) for i in child: print(i.tag, i.text) # 只遍历year 节点 for node in root.iter('year'): print(node.tag, node.text)
范例2:
#!/usr/bin/env python # -*- coding: utf-8 -*- import xml.etree.cElementTree 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") tree.write("xmltest.xml") # 删除node for country in root.findall('country'): rank = int(country.find('rank').text) if rank > 50: root.remove(country) tree.write('output.xml')
PyYAML
类似xml,也是一种文档格式。
参考文档:http://pyyaml.org/wiki/PyYAMLDocumentation
configparser
import configparser
· 用于生成和修改常见配置文档。
· 文档饭粒
#!/usr/bin/env python # -*- coding: utf-8 -*- 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)
posted on
浙公网安备 33010602011771号