Skip to Content
Python实用技能学习指南
book

Python实用技能学习指南

by Posts & Telecom Press, Robert Smallshire, Austin Bingham
February 2024
Intermediate to advanced
316 pages
3h 47m
Chinese
Packt Publishing
Content preview from Python实用技能学习指南

第9章 文件和资源管理

在许多真实世界的程序中,读写文件可能是关键部分。然而,文件的概念有些抽象。在某些情况下,文件可能意味着硬盘上的字节集合;在某些情况下,它可能意味着远程系统上的HTTP资源。这两种情况有一些行为是相同的。例如,你可以从它们中读取一个字节序列。同时,这两种情况并不完全相同。例如,通常可以将字节写回到本地文件,而在使用HTTP资源时,你却无法执行该操作。

在本章中,我们将学习Python对文件的基本支持。处理本地文件比较普遍也比较重要,因此我们将主要关注处理本地文件。但请注意,Python及其生态系统库为许多其他类型的实体(包括基于URI的资源、数据库和许多其他数据源)提供了类似的类文件的API。这种通用API的使用很方便,用它们可以很容易地编写出适用于广泛的数据源的代码而无须任何修改。

在本章中,我们将学习上下文管理器(context manager),它是Python管理资源的主要手段之一。面对异常时,使用上下文管理器可以编写出健壮且可预测的代码,确保在发生错误时能够正确地关闭文件等资源。

要在Python中打开一个本地文件,我们可以使用内置的open()函数。该函数需要一些参数,最常用的是以下几个。

  • file:文件的路径。这是必需的。 
  • mode:读取、写入、追加二进制或文本。这是可选的,但我们建议始终应明确指出。显式比隐式更好。 
  • encoding:文件包含哪种编码文本数据,就使用哪种编码。最好指定编码。如果不指定它,Python会选择一个默认编码。

当然,在文件系统级别上,文件只包含一系列字节。但是,Python会区分以二进制和文本模式打开的文件,即使底层操作系统不区分。当用二进制模式打开一个文件时,你指示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

人工智能技术与大数据

人工智能技术与大数据

Posts & Telecom Press, Anand Deshpande, Manish Kumar
Kafka权威指南(第2版)

Kafka权威指南(第2版)

Gwen Shapira, Todd Palino, Rajini Sivaram, Krit Petty

Publisher Resources

ISBN: 9781835889626