PythonCookBook笔记——数据编码和处理
数据编码和处理
主要涉及用Python处理不同方式编码的数据,如CSV、JSON、XML和二进制包装记录。
读写CSV数据
使用csv库。
import csv
with open('stocks.csv') as f:
f_csv = csv.reader(f)
headers = next(f_csv)
for row in f_csv:
# Process row
...
# row是每行的列表,其中的值通过下标访问
import csv
with open('stocks.csv') as f:
f_csv = csv.DictReader(f)
for row in f_csv:
# process row
...
# 通过字典方式读取,row是一个字典,可通过`row[name]`访问对应值
写入时要先创建一个writer对象。
headers = ['Symbol','Price','Date','Time','Change','Volume']
rows = [('AA', 39.48, '6/11/2007', '9:36am', -0.18, 181800),
('AIG', 71.38, '6/11/2007', '9:36am', -0.15, 195500),
('AXP', 62.58, '6/11/2007', '9:36am', -0.46, 935000),
]
with open('stocks.csv','w') as f:
f_csv = csv.writer(f)
f_csv.writerow(headers)
f_csv.writerows(rows)
对于字典型数据写入,创建DictWriter对象。
headers = ['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume']
rows = [{'Symbol':'AA', 'Price':39.48, 'Date':'6/11/2007',
'Time':'9:36am', 'Change':-0.18, 'Volume':181800},
{'Symbol':'AIG', 'Price': 71.38, 'Date':'6/11/2007',
'Time':'9:36am', 'Change':-0.15, 'Volume': 195500},
{'Symbol':'AXP', 'Price': 62.58, 'Date':'6/11/2007',
'Time':'9:36am', 'Change':-0.46, 'Volume': 935000},
]
with open('stocks.csv','w') as f:
f_csv = csv.DictWriter(f, headers)
f_csv.writeheader()
f_csv.writerows(rows)
读写JSON数据
json模块提供了很简单的方式来编解码JSON数据。
import json
data = {
'name' : 'ACME',
'shares' : 100,
'price' : 542.23
}
json_str = json.dumps(data)
data = json.loads(json_str)
JSON编码支持基本数据类型None、bool、int、float、str以及包含这些类型的list、tuple和dict,对于dict的keys必须是字串类型,并且应该只编码list和dict。
JSON编码对于Python字典,除了True变成true,False变成false,None变成null,没有区别了。
如果要让JSON数据更美观打印出来,使用pprint.pprint()方法。
与关系型数据库进行交互
最好使用列表元组格式数据。
编解码Base64数据
base64模块有两个函数b64encode()和b64decode()可以完成编解码。
>>> import base64
>>> s = b'hello'
>>> a = base64.b64encode(s)
>>> a
b'aGVsbG8='
>>> base64.b64decode(a)
b'hello'
>>>
base64只能处理字节字串或数组,如果要处理文本字串,需要增加一个编解码到字节码的过程。
读写二进制数组数据
使用struct模块处理二进制数据。
from struct import Struct
def write_records(records, format, f):
'''
Write a sequence of tuples to a binary file of structures.
'''
record_struct = Struct(format)
for r in records:
f.write(record_struct.pack(*r))
# Example
if __name__ == '__main__':
records = [ (1, 2.3, 4.5),
(6, 7.8, 9.0),
(12, 13.4, 56.7) ]
with open('data.b', 'wb') as f:
write_records(records, '<idd', f)
以块形式读取文件。
from struct import Struct
def read_records(format, f):
record_struct = Struct(format)
chunks = iter(lambda: f.read(record_struct.size), b'')
return (record_struct.unpack(chunk) for chunk in chunks)
# Example
if __name__ == '__main__':
with open('data.b','rb') as f:
for rec in read_records('<idd', f):
# Process rec
...
一次性读取。
from struct import Struct
def unpack_records(format, data):
record_struct = Struct(format)
return (record_struct.unpack_from(data, offset)
for offset in range(0, len(data), record_struct.size))
# Example
if __name__ == '__main__':
with open('data.b', 'rb') as f:
data = f.read()
for rec in unpack_records('<idd', data):
# Process rec
...
结构体使用了一些结构码如i, d, f等,<表示字节顺序低位在前。
结构体的size属性包含结构的字节数,pack()和unpack()方法被用来打包和解包数据。
PythonCookBook笔记——数据编码和处理的更多相关文章
- PythonCookBook笔记——函数
函数 可接受任意数量参数的函数 接受任意数量的位置参数,使用*参数. 接受任意数量的关键字参数,使用**参数. 只接受关键字参数的函数 强制关键字参数放在某个参数后或直接单个之后. 给函数参数增加元信 ...
- PythonCookBook笔记——文件与IO
文件与IO 所有的程序都要处理输入与输出,涉及到文本.二进制文件.文件编码和对文件名.目录的操作. 读写文本数据 需要读写各种不同编码的文本数据,使用rt模式的open()函数. 该读写操作使用系统默 ...
- PythonCookBook笔记——迭代器与生成器
迭代器与生成器 迭代是Python最强大的功能之一,虽然看起来迭代只是处理序列中元素的一种方法,但不仅仅如此. 手动遍历迭代器 想遍历但不想使用for循环. 使用next()方法并在代码中捕获Stop ...
- PythonCookBook笔记——数字日期和时间
数字日期和时间 数字的四舍五入 用round函数,指定值和小数位数. >>> round(1.23, 1) 1.2 >>> round(1.27, 1) 1.3 & ...
- PythonCookBook笔记——字符串和文本
字符串和文本 使用多个分隔符分割字串 使用正则re.split()方法. >>> line = 'asdf fjdk; afed, fjek,asdf, foo' >>& ...
- PythonCookBook笔记——数据结构和算法
数据结构和算法 解包赋值 p = [1, 2, 3] a, b, c = p # _表示被丢弃的值 _, d, _ = p # 可变长解包 *a, b = p # 字串切割解包 line = 'nob ...
- python-cookbook读书笔记
今天开始读<python-cookbook>,书里有许多python优雅的写法,可以作为python的一本进阶书. 感谢译者.项目地址: https://github.com/yidao6 ...
- 射频识别技术漫谈(4)——数据编码【worldsing 笔记】
前已述及,射频识别技术中的调制方法一般使用调幅(AM),也就是将有用信号调制在载波的幅度上传送出去.这里的"有用信号"指用高低电平表示的数据"0"或" ...
- python3-cookbook笔记:第六章 数据编码和处理
python3-cookbook中每个小节以问题.解决方案和讨论三个部分探讨了Python3在某类问题中的最优解决方式,或者说是探讨Python3本身的数据结构.函数.类等特性在某类问题上如何更好地使 ...
随机推荐
- 【HDOJ6224】Legends of the Three Kingdoms(概率DP)
题意:三国杀,给定4个白板武将的血量,4个角色轮流行动,每回合行动时如果该人存活则可以选择使阵营不同的角色血量-1,血量为0则死亡.每个人按自己获胜概率最大化行动,如果有多种方案概率相同则等概率选择这 ...
- 转 php simple test
转自 后期移至 以下为汪大哥写的 yunlian服务监控 如何写监控代码 首先在tests目录下新建一个文件xxx.php.其中xxx为你的服务名. class XxxTestCase extends ...
- scanf()总结--从网上收来的,感觉很好,用来提醒自己,c语言真是博大精深!!【转】
转自:http://www.cnblogs.com/xiaocai905767378/archive/2011/06/01/2067526.html scanf杂谈 不得不说C语言真 ...
- SPI设备的驱动
主要包括两个SPI设备步骤:register_chrdevspi_register_driver关键点1:spi_board_info可以去已经运行的板子下面找例子:/sys/bus/spi/driv ...
- 无密码登录Linux
配置主机A无密码登录主机B 主机A:192.168.1.110 主机B:192.168.1.111 先确保所有主机的防火墙处于关闭状态. 在主机A上执行如下: 1. $cd ~/.ssh 2. $ss ...
- LeetCode OJ——Validate Binary Search Tree
http://oj.leetcode.com/problems/validate-binary-search-tree/ 判断一棵树是否为二叉搜索树.key 是,在左子树往下搜索的时候,要判断是不是子 ...
- Codeforces Gym101606 I.I Work All Day (2017 United Kingdom and Ireland Programming Contest (UKIEPC 2017))
I I Work All Day 这个题就是取模找最小的. 代码: 1 #include<iostream> 2 #include<cstdio> 3 #include< ...
- Spring Boot + Elastic stack 记录日志
原文链接:https://piotrminkowski.wordpress.com/2019/05/07/logging-with-spring-boot-and-elastic-stack/ 作者: ...
- IDEA连接linux服务器
idea连接linux(完成了xshell和xftp连接linux的功能,可以直接卸载这俩了..) File->settings->Deployment左侧加号添加 选择传输类型ftp或者 ...
- SVG动画基础篇
参考资料: http://www.w3school.com.cn/svg/index.asp https://msdn.microsoft.com/zh-cn/library/gg193979 gi ...