Python入门教程第68篇 读取文本文件

Posted 不剪发的Tony老师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python入门教程第68篇 读取文本文件相关的知识,希望对你有一定的参考价值。

本篇开始我们将会学习 Python 操作文件的方法,首先是如何读取文本文件。

快速参考

以下代码演示了如何从 readme.txt 文件中读取全部文本内容:

with open('readme.txt') as f:
    lines = f.readlines()

读取文本文件的步骤

在 Python 中读取文本文件的步骤如下:

  • 首先,利用 open() 函数以读取模式打开一个文本文件。
  • 其次,使用文件对象的 read()、readline() 或者 readlines() 方法读取文件中的文本。
  • 最后,使用文件对象的 close() 方法关闭文件。

open() 函数

open() 函数支持多个参数,主要的参数包含两个:

open(path_to_file, mode)

path_to_file 参数指定了文本文件的路径。如果文件和程序在同一个目录中,只需要指定文件名即可。否则,我们需要指定完整的路径和文件名。对于 Windows 文件路径,我们可以使用斜杠(/)替代双反斜杠(\\\\)。例如“c:/sample/readme.txt”。

mode 是一个可选的参数,用于指定打开文件的模式。下表列出了可用的模式:

模式描述
‘r’以读取模式打开文本文件
‘w’以写入模式打开文本文件
‘a’以追加模式打开文本文件

例如,以下代码表示以读取模式打开程序目录中的 the-zen-of-python.txt 文件:

 f = open('the-zen-of-python.txt','r')

open() 函数返回了一个文件对象,用于读取文件中的内容。

读取文件内容

文件对象提供读取文本文件内容的三种方法:

  • read() – 读取全部文本,返回一个字符串。这种方法适用于一次性处理小的文件。
  • readline() – 按行读取文件,每次返回一个字符串。
  • readlines() – 读取全部文本,返回一个字符串列表。

close() 方法

在我们使用 close() 方法关闭文件之前,它会一直保持打开状态。及时关闭不再使用的文件非常重要,如果不关闭文件,程序可能会崩溃,或者文件可能被损坏。

以下代码调用 close() 方法关闭打开的文件:

f.close()

为了自动关闭文件,可用使用 with 语句:

with open(path_to_file) as f:
    contents = f.readlines()

在实际使用中,我们可用使用 with 语句自动关闭文件,而不需要手动执行 close() 方法。

示例

我们使用 the-zen-of-python.txt 文件进行演示,该文件的内容如下:

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

以下示例使用 read() 方法读取了该文件中的内容,并将其存入一个字符串对象:

with open('the-zen-of-python.txt') as f:
    contents = f.read()
    print(contents)

输出结果如下:

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
...

以下示例使用 readlines() 方法读取文件,返回了一个字符串列表:

lines = []
with open('the-zen-of-python.txt') as f:
    lines = f.readlines()

count = 0
for line in lines:
    count += 1
    print(f'line count: line')    

输出结果如下:

line 1: Beautiful is better than ugly.

line 2: Explicit is better than implicit.

line 3: Simple is better than complex.
...

以下示例使用 readline() 方法逐行读取文件内容:

with open('the-zen-of-python.txt') as f:
    line = f.readline()
    while line:
        line = f.readline()
        print(line)

输出结果如下:

Explicit is better than implicit.

Simple is better than complex.

Complex is better than complicated.
...

逐行读取文件的简洁方法

open() 函数返回一个可遍历的文件对象。因此,我们可用使用 for 循环逐行遍历文件内容:

with open('the-zen-of-python.txt') as f:
    for line in f:
        print(line)

读取 UTF-8 编码文件

上面的示例代码可以读取 ASCII 编码的文本文件。但是如果我们需要处理其他语言,例如汉字,文件的编码不会使用 ASCII,而很可能是 UTF-8。

为了打开 UTF-8 文件,我们需要为 open() 函数传递一个 encoding=‘utf-8’ 参数。为了演示,我们创建以下 quotes.txt 文件,编码格式为 UTF-8:

春眠不觉晓,处处闻啼鸟。
夜来风雨声,花落知多少。

以下代码演示了如何读取该文件:

with open('quotes.txt', encoding='utf8') as f:
    for line in f:
        print(line.strip())

总结

  • 使用 open() 函数和 ‘r’ 参数以读取模式打开文本文件。
  • 使用 read()、readline() 或者 readlines() 读取文件内容。
  • 读取文件之后使用 close() 方法关闭文件,或者使用 with 语句自动关闭文件。
  • 使用 encoding=‘utf-8’ 读取 UTF-8 编码格式的文件。

以上是关于Python入门教程第68篇 读取文本文件的主要内容,如果未能解决你的问题,请参考以下文章

Python入门教程第69篇 写入文本文件

Python入门教程第70篇 创建文本文件

超简单的Python教程系列——第12篇:文件处理

如何使用Python脚本从PDF中读取阿拉伯语文本

Python入门教程第74篇 文件目录

Python入门教程第65篇 __name__变量