Python3.5内置模块详解:shelve、xml、configparser、hashlib与hmac
95 浏览量
更新于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处理、配置管理、数据校验和安全通信等方面有着广泛的应用。通过熟练掌握这些模块,开发者可以更高效地处理各种数据和任务。
107 浏览量
128 浏览量
196 浏览量
145 浏览量
604 浏览量
2022-06-26 上传
140 浏览量
259 浏览量

weixin_38599231
- 粉丝: 3
最新资源
- Android PRDownloader库:支持文件下载暂停与恢复功能
- Xilinx FPGA开发实战教程(第2版)精解指南
- Aprilstore常用工具库的Java实现概述
- STM32定时开关模块DXP及完整项目资源下载指南
- 掌握IHS与PCA加权图像融合技术的Matlab实现
- JSP+MySQL+Tomcat打造简易BBS论坛及配置教程
- Volley网络通信库在Android上的实践应用
- 轻松清除或修改Windows系统登陆密码工具介绍
- Samba 4 2级免费教程:Ubuntu与Windows整合
- LeakCanary库使用演示:Android内存泄漏检测
- .Net设计要点解析与日常积累分享
- STM32 LED循环左移项目源代码与使用指南
- 中文版Windows Server服务卸载工具使用攻略
- Android应用网络状态监听与质量评估技术
- 多功能单片机电子定时器设计与实现
- Ubuntu Docker镜像整合XRDP和MATE桌面环境