如何使用 Python 从文本文件中读取整行?

programmingpythonserver side programming更新于 2025/3/19 22:04:17

在 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() 函数以读取模式打开文件以实现此目的。使用 open() 在 while 循环内返回的文件处理程序来读取行。

while 循环使用 Python readline() 方法读取行。使用 for 循环时,当到达文件末尾时,循环结束。但是,使用 while 循环时情况并非如此,您必须不断检查文件是否已完成读取。因此,只要 readline() 方法返回空字符串,您就可以使用 break 语句来结束 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!

相关文章


有用资源