Skip to Content
Python面向对象编程指南
book

Python面向对象编程指南

by Posts & Telecom Press, Steven F. Lott
February 2024
Intermediate to advanced
470 pages
7h 41m
Chinese
Packt Publishing
Content preview from Python面向对象编程指南

第9章 序列化和保存——JSON、YAML、Pickle、CSV和XML

为了存储Python中的对象,必须先将其转换为字节,然后再将字节写入文件。这个过程称为序列化,又叫作数据转换(marshaling)、压缩(deflating)或编码(encoding)。接下来我们会介绍几种将一个Python对象转换为字符串或字节流的方式。

每种序列化方式又称为物理数据格式,每种格式各有优缺点。对于呈现对象的方式而言,没有所谓最好的格式。我们需要和逻辑数据格式区分开,它只是简单地将字节流重新排列或改变空格的使用方式,而并未改变对象的值,只是对字节流的操作。

比较重要的一点是(尤其是CSV格式),这些表达方式只是在表达一个单一的Python对象。然而这个单一的对象可以是一组对象的集合,范围是固定的。为了处理这些对象中的一个,必须对整个集合进行反序列化,完成增量序列化需要额外的工作量。不必下太多工夫在如何使用不同格式处理多个对象的序列化,第10章“用Shelve保存和获取对象”、第11章“用SQLite保存和获取对象”和第12章“传输和共享对象”会介绍更好的方式来处理多个不同的对象。

正因为这些方式中的每一个都是针对单一的对象,所以我们无法在对象集合的内存使用方面做太多的控制。当需要处理大量不同的项时,并不能一次性把它们加载到内存,我们无法直接使用这些技术。这时,就需要移至更大的数据库、服务器或消息队列中。现在我们来了解如下几种序列化的表示方式。

  • JavaScript Object Notation(JSON):这是一种被广泛使用的表示方式。更多信息可以参见:http://www.json.orgjson模块提供了用于加载和转储数据所需要的类与函数,都是关于json格式操作。在Python标准库中,可以看一下第19节“网络数据处理”,而不是第12节“存储”。与一般的Python对象的存储问题相比, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

Python语言及其应用(第2版)

Python语言及其应用(第2版)

Bill Lubanovic
Python设计模式(第2版)

Python设计模式(第2版)

Posts & Telecom Press, Chetan Giridhar
可编程网络自动化

可编程网络自动化

Jason Edelman, Scott S. Lowe, Matt Oswalt

Publisher Resources

ISBN: 9781835889541