Python3.5内置模块详解:shelve、xml、configparser、hashlib与hmac
23 浏览量
更新于2024-09-02
收藏 101KB PDF 举报
本文主要探讨了Python3.5中的五个内置模块:shelve、xml、configparser、hashlib以及hmac,并提供了相应的实例解析它们的功能和使用方式。
1、shelve模块
shelve模块提供了一个简单的键值对存储机制,用于持久化Python对象。它通过pickle模块将数据序列化,使得在存储和读取时能保持对象的原始状态。下面是一个使用shelve模块的例子:
```python
import shelve
import datetime
# 打开一个shelve文件
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()
# 关闭shelve文件
d.close()
```
读取shelve中的数据,可以通过get方法完成:
```python
import shelve
import datetime
# 打开shelve文件
d = shelve.open('shelve_test')
# 读取存储的数据
print(d.get("name")) # 输出列表
print(d.get("info")) # 输出字典
print(d.get("data")) # 输出日期时间对象
# 关闭shelve文件
d.close()
```
2、xml模块
Python的xml模块用于处理XML文档,包括解析XML文档、创建XML文档、操作XML元素树等。例如,可以使用ElementTree API来解析XML文件:
```python
import xml.etree.ElementTree as ET
# 解析XML文件
tree = ET.parse('example.xml')
root = tree.getroot()
# 遍历XML元素
for child in root:
print(child.tag, child.attrib)
```
3、configparser模块
configparser模块用于读写INI格式配置文件,常用于保存应用的设置。下面是一个使用configparser的例子:
```python
import configparser
# 创建配置文件
config = configparser.ConfigParser()
config['DEFAULT'] = {'ServerAliveInterval': '45'}
config['COMPUTER1'] = {'Host': 'alpha', 'IP': '192.168.1.1'}
config['COMPUTER2'] = {'Host': 'beta', 'IP': '192.168.1.2'}
# 将配置写入文件
with open('config.ini', 'w') as configfile:
config.write(configfile)
# 读取配置文件
config = configparser.ConfigParser()
config.read('config.ini')
# 输出配置信息
print(config['COMPUTER1']['Host'])
print(config['COMPUTER1']['IP'])
```
4、hashlib模块
hashlib模块提供了各种哈希函数,如MD5、SHA1、SHA256等,用于计算字符串的哈希值。例如,计算一个字符串的SHA256哈希:
```python
import hashlib
message = 'Hello, World!'
hash_object = hashlib.sha256(message.encode())
hex_dig = hash_object.hexdigest()
print(hex_dig)
```
5、hmac模块
hmac模块用于生成消息认证码(HMAC),它结合了密钥和哈希函数,用于验证数据的完整性和来源。以下是如何使用hmac模块生成HMAC的示例:
```python
import hmac
import hashlib
key = b'secret key'
message = b'Hello, HMAC!'
hmac_digest = hmac.new(key, message, hashlib.sha256).digest()
print(hmac_digest)
```
以上五个模块是Python3.5中常用的内置模块,它们分别在数据持久化、XML处理、配置管理、数据校验和安全通信等方面有着广泛的应用。通过熟练掌握这些模块,开发者可以更高效地处理各种数据和任务。
2315 浏览量
4823 浏览量
128 浏览量
107 浏览量
196 浏览量
145 浏览量
604 浏览量
2022-06-26 上传

weixin_38599231
- 粉丝: 3
最新资源
- HL-340 USB转串口驱动安装指南
- 掌握编程规范,提升软件工程师高级程序修养
- 封装技术在layer3弹层中的应用与优化
- 快速找回遗忘网页星号密码技巧
- 亚马逊FBA发货全指南:避免拒收的策略和技巧
- 麻省理工算法导论课件解析
- Spring框架结合MongoDB的演示项目构建指南
- Symfony MSSQL Bundle:在Unix上通过pdo_dblib增强对MSSQL的支持
- 手机美食餐饮微官网的HTML实现源代码
- React开发新视角:velocity-react组件实现UI动画
- 探索Od反汇编工具的下载与使用
- 一键去除Windows桌面图标阴影教程
- Android动态生成树形结构技术分享
- Maven插件扩展规则详解与使用指南
- 深入学习VTK:开发者指南(第一部分)
- PHP-GTK中文手册:从入门到高级应用教程