python中的xml

写一个XML文件

import xml.etree.ElementTree as ET
namelist=ET.ElementTree("namelist")

namelist生成一个根节点
name=ET.SubElement(namelist,"name",attrib={"strinf":"yes","name":"alex"})

赋予namelist属性
age=ET.SubElement(name,"age")

在根下面建立子节点
age.txt=27

赋值
role=ET.SubElement(name,"role")

根下建立子节点
role.txt="teacher"

et=ET.ElementTree(namelist)

生成文件对象
et.write("test.xml",encoding="utf-8",xml_declaration=True)

写进一个xml文件

 

 

configparser模块:可以生成和修改配置文件

import configparser
config=configparser.ConfigParser()#生成对象
config["DEFAULT"]={'Interval':'45',
                 'Compression':'yes',
                 'CompressionLevel':'9'}

赋予属性,生成字典
config['bitbucket.org']={}可以单独生成
config['bitbucket.org']['User']='alex'#赋值
config['topsecret.server.com']={}

topsecret=config['topsecret.server.com']
topsecret['Host Port']='50022'
topsecret['ForwardXll']='no'
topsecret['enabled']='YES'

config['DEFAULT']['ForwardXll']='yes'
f=open("config.ini",'w')

config.write(f)
f.close()

 

在生成的文件中增删改

import configparser
config=configparser.ConfigParser()
config.read("config1.ini")
print(config.sections())#找到文件的sections
config_name=config.sections()[1]

#找到对应的值
print(config[config_name]["host port"])

sec=config.remove_option(config_name,'forwardxll')
删除forwardx11这一行

config.set(config_name,'host port','3000')

将端口号改为3000
config.write(open("config2.ini","w"))

 

hashlib模块:用来验证文件内容一致性的

import hashlib
m= hashlib.md5()
m.update(b"alex")
print(m.hexdigest())
m.update(b"li")
print(m.hexdigest())

读一行的md5没有比读整篇的md5省内存

m2=hashlib.md5()
m2.update(b"alexli")
print(m2.hexdigest())

 

m2=hashlib.sha256()
m2.update(b"alexli")
print(m2.hexdigest())

sha256的比md5的安全

加盐算法,更安全

import hmac
hamc_name=hmac.new(b"salt",b"hello")
print(hamc_name.hexdigest())

 

 

 

 

 

posted @ 2017-01-13 19:58  python包拯  阅读(450)  评论(0编辑  收藏  举报