前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 将列表写到二进制文件中

python 将列表写到二进制文件中

作者头像
用户5760343
发布2019-10-21 13:04:37
1.8K0
发布2019-10-21 13:04:37
举报
文章被收录于专栏:sktj

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 ...

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019.10.18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Example
  • 读取二进制文件
  • Example
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档