如何使用 Python 读取文本文件中的整行内容?


Python 中有多种读取文件的方式。将介绍在 Python 中逐行读取文件的常用方法。

使用 readlines() 方法

使用此方法,将打开一个文件并将其内容划分为单独的行。此方法还返回文件中每一行的列表。为了有效地读取整个文件,我们可以使用 readlines() 函数。

以下是一个使用 file.endswith() 方法删除交换文件的示例:

示例

以下是如何使用 readlines() 方法逐行读取文本文件的示例:

# opening the data file file = open("TutorialsPoint.txt") # reading the file as a list line by line content = file.readlines() # closing the file file.close() print(content)

输出

以下是上述代码的输出。

['Welcome to Tutorials Point\n', 'This is a new file.\n', 'Reading a file line by line using Python\n', 'Thank You!']

使用 readline() 方法

可以使用 readline() 方法获取文本文件的第一行。当我们使用 readline() 方法读取文件时,与 readlines() 相比,只会打印一行。

示例

以下是如何使用 readline() 方法读取文本文件单行的示例:

file = open("TutorialsPoint.txt") # getting the starting line of the file start_line = file.readline() print(start_line) file.close()

输出

readline() 函数只返回一行文本。如果要一次读取所有行,请使用 readline()。

以下是上述代码的输出:

Welcome to Tutorials Point

注意 - 与其等效方法相反,readline() 方法仅从文件中提取一行。realine() 方法还会在字符串末尾添加一个尾随换行符。

我们还可以使用 readline() 方法为返回的行定义长度。如果没有指定大小,则将读取整行。

使用 While 循环

您可以使用 while 循环逐行读取指定文件的内容。首先使用 open() 函数以读取模式打开文件以实现此目的。在 while 循环内使用 open() 返回的文件句柄来读取行。

while 循环使用 Python 的 readline() 方法读取行。当使用 for 循环时,当文件结束时循环结束。但是,使用 while 循环时,情况并非如此,您必须不断检查文件是否已完成读取。因此,您可以使用 break 语句在 readline() 方法返回空字符串时结束 while 循环。

示例

以下是如何使用 while 循环逐行读取文本文件的示例:

file = open("TutorialsPoint.txt", "r") while file: line = file.readline() print(line) if line == "": break file.close()

输出

以下是上述代码的输出:

Welcome to Tutorials Point
This is a new file.
Reading a file line by line using Python
Thank You!

使用 for 循环

首先使用 Python 的 open() 函数以只读模式打开文件。open() 函数将返回一个文件句柄。在您的 for 循环中,使用文件句柄从提供的文件中一次读取一行。完成后,使用 close() 函数关闭文件句柄。

示例

以下是如何使用 for 循环逐行读取文本文件的示例:

file = open("TutorialsPoint.txt", "r") for line in file: print(line) file.close()

输出

以下是上述代码的输出:

Welcome to Tutorials Point
This is a new file.
Reading a file line by line using Python
Thank You!

使用上下文管理器

任何编程语言都需要对文件管理采取谨慎的方法。处理文件时必须小心,以避免损坏。务必记住在打开文件后关闭资源。此外,Python 对一次可以打开的文件数量有限制。Python 为我们提供了上下文管理器来帮助我们避免这些问题。

如果 Python 使用with语句,则文件处理将是安全的。

  • 要安全地访问资源文件,请使用 with 语句。
  • 当 Python 遇到with块时,它会创建一个新的上下文。
  • Python 在块完成运行后自动关闭文件资源。
  • 上下文的范围类似于with语句。

示例

以下是如何使用 with 语句逐行读取文本文件的示例:

# opening the file with open("TutorialsPoint.txt",'r') as text: # reading the file by using a for loop for line in text: # stripping the newline character from the line print(line.strip())

输出

这次,使用 for 循环读取文件行。当我们使用上下文管理器时,只要其句柄退出作用域,文件就会自行关闭。with 语句确保在函数完成处理文件后正确处理资源。

以下是上述代码的输出

Welcome to Tutorials Point
This is a new file.
Reading a file line by line using Python
Thank You!

更新于: 2022-08-17

14K+ 次查看

开启你的职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.