如何使用 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() 方法获取文本文件的第一行。与 readlines() 相比,当我们使用 readline() 方法读取文件时,只会打印一行。
示例
以下是一个使用 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!
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP