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()函数只返回一行文本。如果你想一次读取所有的行,请使用readlines()。
以下是上述代码的输出结果:
Welcome to Tutorials Point
注意 − readline()方法与其等价物相比,只从文件中提取一行。readline()方法还会在字符串末尾添加一个尾随的换行符。
我们还可以使用readline()方法为返回的行定义一个长度。如果没有指定大小,将会读取整行。
使用while循环
你可以使用while循环逐行读取指定文件的内容。首先使用open()函数以读取模式打开文件来实现这一点。然后将open()返回的文件处理程序用于while循环来读取行。
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!
极客笔记