在Python中逐行读取文件
先决条件:
- 访问模式
- 打开一个文件
- 关闭文件
Python提供了用于创建、写入和读取文件的内置函数。在Python中可以处理两种类型的文件,普通文本文件和二进制文件(用二进制语言编写,0s 和 1s)。在本文中,我们将研究从文件中逐行读取。
逐行阅读
使用 readlines()
readlines() 用于一次读取所有行,然后将它们作为每行返回一个列表中的字符串元素。此函数可用于小文件,因为它将整个文件内容读取到内存中,然后将其拆分为单独的行。我们可以遍历列表并使用 strip()函数去除换行符 '\n'字符。
例子:
Python3
# Python code to
# demonstrate readlines()
L = ["Geeks\n", "for\n", "Geeks\n"]
# writing to file
file1 = open('myfile.txt', 'w')
file1.writelines(L)
file1.close()
# Using readlines()
file1 = open('myfile.txt', 'r')
Lines = file1.readlines()
count = 0
# Strips the newline character
for line in Lines:
count += 1
print("Line{}: {}".format(count, line.strip()))
Python3
# Python program to
# demonstrate readline()
L = ["Geeks\n", "for\n", "Geeks\n"]
# Writing to a file
file1 = open('myfile.txt', 'w')
file1.writelines((L))
file1.close()
# Using readline()
file1 = open('myfile.txt', 'r')
count = 0
while True:
count += 1
# Get next line from file
line = file1.readline()
# if line is empty
# end of file is reached
if not line:
break
print("Line{}: {}".format(count, line.strip()))
file1.close()
Python3
# Python program to
# demonstrate reading files
# using for loop
L = ["Geeks\n", "for\n", "Geeks\n"]
# Writing to file
file1 = open('myfile.txt', 'w')
file1.writelines(L)
file1.close()
# Opening file
file1 = open('myfile.txt', 'r')
count = 0
# Using for loop
print("Using for loop")
for line in file1:
count += 1
print("Line{}: {}".format(count, line.strip()))
# Closing files
file1.close()
Python3
# Python program to
# demonstrate with
# statement
L = ["Geeks\n", "for\n", "Geeks\n"]
# Writing to file
with open("myfile.txt", "w") as fp:
fp.writelines(L)
# using readlines()
count = 0
print("Using readlines()")
with open("myfile.txt") as fp:
Lines = fp.readlines()
for line in Lines:
count += 1
print("Line{}: {}".format(count, line.strip()))
# Using readline()
count = 0
print("\nUsing readline()")
with open("myfile.txt") as fp:
while True:
count += 1
line = fp.readline()
if not line:
break
print("Line{}: {}".format(count, line.strip()))
# Using for loop
count = 0
print("\nUsing for loop")
with open("myfile.txt") as fp:
for line in fp:
count += 1
print("Line{}: {}".format(count, line.strip()))
输出:
Line1: Geeks
Line2: for
Line3: Geeks
使用 readline()
readline()函数读取文件的一行并以字符串的形式返回。它需要一个参数 n,它指定将读取的最大字节数。但是,不会读取超过一行,即使 n 超过了行的长度。读取大文件时会很高效,因为它不是一次性获取所有数据,而是逐行获取。 readline() 返回文件的下一行,最后包含字符。此外,如果到达文件末尾,它将返回一个空字符串。
例子:
Python3
# Python program to
# demonstrate readline()
L = ["Geeks\n", "for\n", "Geeks\n"]
# Writing to a file
file1 = open('myfile.txt', 'w')
file1.writelines((L))
file1.close()
# Using readline()
file1 = open('myfile.txt', 'r')
count = 0
while True:
count += 1
# Get next line from file
line = file1.readline()
# if line is empty
# end of file is reached
if not line:
break
print("Line{}: {}".format(count, line.strip()))
file1.close()
输出:
Line1 Geeks
Line2 for
Line3 Geeks
使用 for 循环
open()函数在打开文件时返回一个可迭代对象。逐行读取文件的最后一种方法包括在 for 循环中迭代文件对象。这样做我们利用了一个内置的Python函数,它允许我们使用 for 循环和使用可迭代对象来隐式地迭代文件对象。这种方法需要更少的代码行,这始终是值得遵循的最佳实践。
例子:
Python3
# Python program to
# demonstrate reading files
# using for loop
L = ["Geeks\n", "for\n", "Geeks\n"]
# Writing to file
file1 = open('myfile.txt', 'w')
file1.writelines(L)
file1.close()
# Opening file
file1 = open('myfile.txt', 'r')
count = 0
# Using for loop
print("Using for loop")
for line in file1:
count += 1
print("Line{}: {}".format(count, line.strip()))
# Closing files
file1.close()
输出:
Using for loop
Line1: Geeks
Line2: for
Line3: Geeks
带声明
在上述方法中,每次打开文件时都需要显式关闭它。如果忘记关闭文件,可能会在代码中引入一些错误,即文件中的许多更改在文件正确关闭之前不会生效。可以使用 with 语句来防止这种情况。 Python中的 With 语句用于异常处理,以使代码更简洁、更具可读性。它简化了文件流等公共资源的管理。观察以下代码示例,了解使用 with 语句如何使代码更简洁。使用 with 语句时无需调用 file.close()。 with 语句本身可确保正确获取和释放资源。
例子:
Python3
# Python program to
# demonstrate with
# statement
L = ["Geeks\n", "for\n", "Geeks\n"]
# Writing to file
with open("myfile.txt", "w") as fp:
fp.writelines(L)
# using readlines()
count = 0
print("Using readlines()")
with open("myfile.txt") as fp:
Lines = fp.readlines()
for line in Lines:
count += 1
print("Line{}: {}".format(count, line.strip()))
# Using readline()
count = 0
print("\nUsing readline()")
with open("myfile.txt") as fp:
while True:
count += 1
line = fp.readline()
if not line:
break
print("Line{}: {}".format(count, line.strip()))
# Using for loop
count = 0
print("\nUsing for loop")
with open("myfile.txt") as fp:
for line in fp:
count += 1
print("Line{}: {}".format(count, line.strip()))
输出:
Using readlines()
Line1: Geeks
Line2: for
Line3: Geeks
Using readline()
Line1: Geeks
Line2: for
Line3: Geeks
Using for loop
Line1: Geeks
Line2: for
Line3: Geeks