溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何在Python3.5中使用shelve模塊和xml模塊

發(fā)布時間:2021-05-12 17:09:27 來源:億速云 閱讀:132 作者:Leah 欄目:開發(fā)技術(shù)

如何在Python3.5中使用shelve模塊和xml模塊?針對這個問題,這篇文章詳細介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

1、shelve模塊

shelve類似于一個key-value數(shù)據(jù)庫,可以很方便的用來保存Python的內(nèi)存對象,其內(nèi)部使用pickle來序列化數(shù)據(jù),

簡單來說,使用者可以將一個列表、字典、或者用戶自定義的類實例保存到shelve中,下次需要用的時候直接取出來,

就是一個Python內(nèi)存對象,不需要像傳統(tǒng)數(shù)據(jù)庫一樣,先取出數(shù)據(jù),然后用這些數(shù)據(jù)重新構(gòu)造一遍所需要的對象。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
import shelve
import datetime
d = shelve.open('shelve_test') # 打開一個文件
info = {
  "age":23,
  "job":"IT"
}
name = ["alex", "rain", "test"]
d["name"] = name # 持久化列表
d["info"] = info # 持久化字典
d["data"] = datetime.datetime.now()
d.close()

運行結(jié)果:產(chǎn)生3個文件

如何在Python3.5中使用shelve模塊和xml模塊

從shelve中數(shù)據(jù)讀?。篻et方法

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
import shelve
import datetime
d = shelve.open('shelve_test') # 打開一個文件
print(d.get("name"))
print(d.get("info"))
print(d.get("data"))

運行結(jié)果:

['alex', 'rain', 'test']
{'job': 'IT', 'age': 23}
2017-09-29 18:31:12.013709

2、xml模塊

xml是實現(xiàn)不同語言或程序之間進行數(shù)據(jù)交換的協(xié)議,跟json差不多,但json使用起來更簡單,在json還沒誕生時,

大家只能選擇用xml,至今很多傳統(tǒng)公司如金融行業(yè)的很多系統(tǒng)的接口還主要是xml。xml的格式如下,就是通過<>節(jié)點來區(qū)別數(shù)據(jù)結(jié)構(gòu)的。

(1)xml文件示例代碼如下:文件名為:xml_test.xml

<?xml version="1.0"?>
<data>
  <country name="Liechtenstein">
    <rank updated="yes">2</rank>
    <year>2008</year>
    <gdppc>141100</gdppc>
    <neighbor name="Austria" direction="E"/>
    <neighbor name="Switzerland" direction="W"/>
  </country>
  <country name="Singapore">
    <rank updated="yes">5</rank>
    <year>2011</year>
    <gdppc>59900</gdppc>
    <neighbor name="Malaysia" direction="N"/>
  </country>
  <country name="Panama">
    <rank updated="yes">69</rank>
    <year>2011</year>
    <gdppc>13600</gdppc>
    <neighbor name="Costa Rica" direction="W"/>
    <neighbor name="Colombia" direction="E"/>
  </country>
</data>

(2)Python中操作xml模塊

xml協(xié)議在各種語言里的都是支持的,在python中可以用以下模塊操作xml 。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
#python中操作xml模塊
import xml.etree.ElementTree as ET
tree = ET.parse("xml_test.xml")  #要處理的xml文件名
root = tree.getroot()  #root是一個內(nèi)存對象
print(root)
print(root.tag)    #打印標簽名
#print(ET.parse("xml_test.xml").getroot().tag)
# 遍歷xml文檔
for child in root:
  print(child.tag, child.attrib)  #打印下一級的標簽名和屬性
  for i in child:
    print(i.tag,i.attrib,i.text)

如何在Python3.5中使用shelve模塊和xml模塊

運行結(jié)果:

<Element 'data' at 0x0062E8A0>
data
country {'name': 'Liechtenstein'}
rank {'updated': 'yes'} 2
year {} 2008
gdppc {} 141100
neighbor {'direction': 'E', 'name': 'Austria'} None
neighbor {'direction': 'W', 'name': 'Switzerland'} None
country {'name': 'Singapore'}
rank {'updated': 'yes'} 5
year {} 2011
gdppc {} 59900
neighbor {'direction': 'N', 'name': 'Malaysia'} None
country {'name': 'Panama'}
rank {'updated': 'yes'} 69
year {} 2011
gdppc {} 13600
neighbor {'direction': 'W', 'name': 'Costa Rica'} None
neighbor {'direction': 'E', 'name': 'Colombia'} None

只遍歷節(jié)點year,代碼如下:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
#python中操作xml模塊
import xml.etree.ElementTree as ET
tree = ET.parse("xml_test.xml")  #要處理的xml文件名
root = tree.getroot()  #root是一個內(nèi)存對象
print(root)
print(root.tag)    #打印標簽名
# 只遍歷year 節(jié)點
for node in root.iter('year'):
  print(node.tag, node.text)

運行結(jié)果:

<Element 'data' at 0x0050E8D0>
data
year 2008
year 2011
year 2011

3、configparser模塊

用于生成和修改常見配置文檔,常見文檔格式如下:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no

Python生成配置文檔:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
#python生成配置文檔
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)

4、hashlib模塊

做一個映射關(guān)系,將字符串轉(zhuǎn)成數(shù)字,用于加密相關(guān)的操作。

3.x里主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
import hashlib
m = hashlib.md5()  #生成對象
m.update(b"Hello")
m.update(b"It's me")
print(m.digest())
m.update(b"It's been a long time since last time we ...")
print(m.digest()) #2進制格式hash
print(len(m.hexdigest())) #16進制格式hash
print(m.hexdigest())
# ######## md5 ########
hash = hashlib.md5()
hash.update(b'admin')
print("md5:",hash.hexdigest())
# ######## sha1 ########
hash = hashlib.sha1()
hash.update(b'admin')
print("sha1:",hash.hexdigest())
# ######## sha256 ########
hash = hashlib.sha256()
hash.update(b'admin')
print("sha256:",hash.hexdigest())

運行結(jié)果:

b']\xde\xb4{/\x92Z\xd0\xbf$\x9cR\xe3Br\x8a'
b'\xa0\xe9\x89E\x03\xcb\x9f\x1a\x14\xaa\x07?<\xae\xfa\xa5'
32
a0e9894503cb9f1a14aa073f3caefaa5
md5: 21232f297a57a5a743894a0e4a801fc3
sha1: d033e22ae348aeb5660fc2140aec35850c4da997
sha256: 8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918

5、hmac 模塊

它內(nèi)部對我們創(chuàng)建 key 和 內(nèi)容 再進行處理然后再加密。

散列消息鑒別碼,簡稱HMAC,是一種基于消息鑒別碼MAC(Message Authentication Code)的鑒別機制。

使用HMAC時,消息通訊的雙方,通過驗證消息中加入的鑒別密鑰K來鑒別消息的真?zhèn)?;一般用于網(wǎng)絡(luò)通信中消息加密。

前提是雙方先要約定好key,就像接頭暗號一樣,然后消息發(fā)送把用key把消息加密,接收方用key + 消息明文再加密,

拿加密后的值 跟 發(fā)送者的相對比是否相等,這樣就能驗證消息的真實性,及發(fā)送者的合法性了。

import hmac
h = hmac.new(b'zxc', 'cvb你好'.encode(encoding="utf-8"))
print(h.digest())
print(h.hexdigest())
#運行結(jié)果:
#b'\xc1\x89\t#VQ\xa4\x00\xbf\xed\xb2_\xc1s\xfa\xd2'
#c18909235651a400bfedb25fc173fad2

關(guān)于如何在Python3.5中使用shelve模塊和xml模塊問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細節(jié)
推薦閱讀:
  1. Python - xml模塊
  2. xml模塊

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI