Skip to Content
Python入门指南, 3rd Edition
book

Python入门指南, 3rd Edition

by Bill Lubanovic
September 2025
Intermediate to advanced
660 pages
7h 15m
Chinese
O'Reilly Media, Inc.
Content preview from Python入门指南, 3rd Edition

第 20 章 文件 文件

本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com

我们有持久对象,它们被称为文件。

肯-汤普森

刚开始编程时,你会反复听到一些词,但不确定它们是否有特定的技术含义,还是只是随口说说而已。 术语 "文件"和 "目录"就是这样的词,它们确实有实际的技术含义。文件是字节序列,存储在文件系统中,通过文件名访问。目录是文件的集合,也可能是其他目录的集合。文件夹目录的同义词。当计算机获得图形用户界面时,它就出现了,并模仿办公室的概念,使概念看起来更熟悉。

许多文件系统都是分层的,通常被称为树形系统,但真实的办公室并没有树形系统,只有将子文件夹一直向下可视化,文件夹的类比才有效。

文件输入和输出

最简单的持久化是一个普通的老文件,有时 称为平面文件。您可以从文件读入内存,也可以从内存写入文件。 Python 使这些工作变得简单。 与许多语言一样,它的文件操作在很大程度上是以熟悉和流行的 Unix 对应文件为模型的。

使用 open() 创建或打开文件

在执行以下操作之前,,需要调用open() 函数:

  • 读取现有文件

  • 写入新文件

  • 追加到现有文件

  • 覆盖现有文件

下面简要解释一下该调用的各个部分:

fileobj = open( filename, mode )
  • fileobjopen() 返回的文件对象。

  • filename是文件的字符串名称。

  • mode是一个字符串,表示文件类型和要对其做的操作。

第一个字母 mode的第一个字母表示操作

  • r 表示读取

  • w 表示写入。如果文件不存在,则创建该文件;如果文件存在,则覆盖该文件。

  • x 表示写入,但仅限于文件存在的情况。

  • a 表示附加(在结尾后写入),如果文件存在。

的第二个字母 mode文件类型

  • t (或没有)表示文本

  • b 表示二进制

打开文件后,调用函数读取或写入数据;这些将在后面的示例中展示。

最后,你需要关闭文件,以确保所有写入都已完成,内存也已释放。稍后,你将看到如何使用with 自动完成这项工作。

该程序会打开一个名为oops.txt 的文件,并在不写入任何内容的情况下将其关闭。 这样就创建了一个空文件:

>>> fout = open('oops.txt', 'wt')
>>> fout.close()

使用 print() 写入文本文件

让我们在 重新创建oops.txt,但现在要在其中写一行内容,然后关闭它:

>>> fout = open('oops.txt', 'wt')
>>> print('Oops, I created a file.', file=fout)
>>> fout.close()

在上一节中,我们创建了一个空的oops.txt文件,因此这只是覆盖它。

我们使用file 作为print() 的参数。没有这个参数,print() 会写入标准输出,也就是你的终端(除非你用>告诉 shell 程序将输出重定向到一个文件,或者用| 将输出管道化到另一个程序)。

使用 write() 写入文本文件

print() 我们刚刚使用将一行写入文件。我们也可以使用write()

对于我们的多行数据源,让我们使用这首关于狭义相对论的打油诗:1

>>> poem = '''There was a young lady named Bright,
... Whose speed was far faster than ...
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

生成式人工智能设计模式

生成式人工智能设计模式

Valliappa Lakshmanan, Hannes Hapke

Publisher Resources

ISBN: 9798341668898