python xml 与配置文件处理

import xml.etree.ElementTree as ET
'''
xml处理模块
'''
from idlelib.IOBinding import encoding
 
 
tree = ET.parse("xmltest.xml")

#获取root
root = tree.getroot()
print(root)

#遍历xml
for child in root:
    print(child.tag,child.attrib)
    for i in child:
        print(i.tag,i.text)

#只遍历body 节点
for node in root.iter('body'):
    print(node.tag,node.text)
    
    

'''
修改
'''
for node in root.iter('from'):
#修改text
    node.text="newValue" 
#修改属性
    node.set("test","2")
tree.write("xmltest.xml")
    
    
'''
删除
'''
for node in root.findall('heading'):
    root.remove(node)
    
tree.write("xmltest_delete.xml")
    
    
    
    
'''
创建
'''
 
new_xml = ET.Element("nameList")
info= ET.SubElement(new_xml,"info",attrib={"encrypt":"yes"})
name = ET.SubElement(info,"name")
age = ET.SubElement(info,"age")
age.text= '23'
name.text = "jack"

info2 = ET.SubElement(new_xml,"info",attrib={"encrypt":"no"})
age = ET.SubElement(info2,"age")
name = ET.SubElement(info2,"name")
age.text= '25'
name.text = "flack"

et = ET.ElementTree(new_xml)
et.write("new_xml.xml",encoding="utf-8",xml_declaration=True)
ET.dump(new_xml)

 

xmltest.xml:
<note> 
  <to>Tove</to>  
  <from test="1">www</from>  
  <heading>Reminder</heading>  
   <heading>adwwwee</heading>  
  <body>Don't forget me this weekend!</body>  
  <body>aaaaaaaaaa</body>  
  <body>bbbbbbbbbbb</body>  
  <body> 
    <test>cccccccccc</test> 
  </body> 
</note>

 

 

 

 

配置文件处理:

# -*- coding: utf-8 -*-
import configparser

'''
处理配置文件的模块 , 比如处理MySQL 的配置文件
'''

'''
创建一个配置文件
'''
config = configparser.ConfigParser()

config["DEFAULT"] = {"ServerAliveInterval":"45",
                    "Compression":"yse",
                    "CompressionLevel":"9"
                     }

config["bitbucket.org"]={}
config["bitbucket.org"]["User"]="HG"

f = open("example.ini","w")
config.write(f)

f.close()




'''
读取
'''
config = configparser.ConfigParser()
config.sections()
config.read("example.ini")


#打印 sections
print(config.sections())

#打印default
print(config.defaults())

#获取指定的value 
print(config["DEFAULT"]["ServerAliveInterval"])



'''
删除
删除topsecret.server.com
'''
sec = config.remove_section("topsecret.server.com")
config.write(open("new_cofig.ini","w"))

 

example.ini:
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9

[bitbucket.org]
User = ha

[topsecret.server.com]
Port = 1521

 

posted on 2017-11-10 15:40  gaizhongfeng  阅读(1098)  评论(0编辑  收藏  举报