1. 程式人生 > >shelve,xml,configparser,hashlib

shelve,xml,configparser,hashlib

#shelve模組

import shelve
d=shelve.open('shelve_test')

t = Tes(123)
t2 = Tes(123334)

name = ["alex", "rain", "test"]
d["test"] = name  # 持久化列表
d["t1"] = t  # 持久化類
d["t2"] = t2

d.close()
#寫
import shelve,datetime
d = shelve.open('shelve_test')
info = {'age':22,'job':'it'}
name = ['alex','rain','test']
d['name'

]=name
d['info']=info
d['date']=datetime.datetime.now()
d.close()

#讀
import shelve
d = shelve.open('shelve_test')
print(d.get('name'))
print(d.get('info'))
print(d.get('date'))

 

#xml模組

import xml.etree.ElementTree as ET
tree = ET.parse("xmltes.xml")
root=tree.getroot()
#print(root) #文件記憶體地址
#print(root.tag) #根的名 標籤名



#遍歷 xml文件
for  child in root:
    print(child.tag,child.attrib)
    for i in child:
        print(i.tag,i.text,i.attrib #attrib屬性 text內容
        

#只遍歷year節點
for node in root.iter('year'
):
    print(node.tag,node.text)

#修改xml文件
for node in root.iter('year'):
    new_year = int(node.text) + 1
    node.text=str(new_year)
    node.set("updated","yes") #修改屬性

tree.write("xmltes.xml") #寫回原檔案

#刪除node
for country in root.findall('country'):
    rank=int(country.find('rank').text)
    if rank > 50:
        root.remove(country)
tree.write('output.xml')

#建立xml
new_xml=ET.Element("personinfolist")
personinfo=ET.SubElement(new_xml,'personinfo',attrib={"enrolled":"yes"})
name=ET.SubElement(personinfo,"name")
name.text="alex"
age=ET.SubElement(personinfo,'age',attrib={"checked":"no"})
sex=ET.SubElement(personinfo,"sex")
age.text="88"
personinfo2=ET.SubElement(new_xml,'personinfo',attrib={"enrolled":"no"})
name=ET.SubElement(personinfo2,"name")
name.text="haha"
age=ET.SubElement(personinfo2,"age")
age.text='19'

et=ET.ElementTree(new_xml) #生成文件物件
et.write("tes.xml",encoding="utf-8",xml_declaration=True)
ET.dump(new_xml)#列印生成的格式

 

Configparser模組

#用於生成和修改常見配置文件
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','w') as configfile:
    config.write(configfile)
#讀配置檔案
conf=configparser.ConfigParser()
conf.read("example")
print(conf.defaults())
print(conf['bitbucket.org']['user'])    #section部分

#刪除section
sec = conf.remove_section('bitbucket.org') #section部分 刪除bitbucket.org部分
conf.write(open('example.cfg','w')) #寫入 可修改原檔案

#判斷section部分
print(conf.has_section("topsecret.server.com")) #存在則為true

#新增section
sec2=conf.add_section("HOST")
conf.write(open('example.cfg','w'))


#修改section下的key value
conf.set('HOST','hostname_ip','192.168.0.1')  #conf.set(section,'key','value')
conf.write(open('example.cfg','w'))

 

#hashlib模組

import hashlib
#用於加密相關的操作
m = hashlib.md5()
m.update(b'hello') #update疊加
print(m.hexdigest()) #十六進位制
m.update(b"It's me")
print(m.hexdigest())
m.update(b"It's been a long time since last time we ...")
print(m.hexdigest())

print('----------------------------------------')

m2=hashlib.md5()
m2.update(b"helloIt's me")  #拼起來
print(m2.hexdigest())


s2=hashlib.sha256()
s2.update(b"helloIt's me")
print(s2.hexdigest())

import hmac
#對我們建立 key 和 內容 再進行處理然後再加密 用於訊息加密
h = hmac.new('天王蓋地虎'.encode(encoding="utf-8"),'寶塔鎮河妖'.encode(encoding='utf-8'))
print(h.digest()) #十進位制
print(h.hexdigest())