Python 逐行读取文件的 5 种方式

在本文中,我们将讨论在 Python 中逐行读取文件的不同方法。

假设在与 Python 脚本相同的目录下有一个名为 data.txt 的文件。以下是逐行读取其内容的几种常见方案。

方法一:使用 readlines() 获取所有行列表

这是一个基础但效率较低的解决方案,适用于小型文件

通过文件对象调用 readlines() 函数,会将整个文件内容读取到内存中,分割为单独的行,并返回一个包含所有行的列表。除最后一行外,列表中的每个字符串末尾通常包含换行符。

示例代码如下:

# 打开文件
fileHandler = open("data.txt", "r")
# 获取文件中所有行的列表
listOfLines = fileHandler.readlines()
# 关闭文件
fileHandler.close()

# 遍历列表
for line in listOfLines:
    print(line.strip())

输出:

Hello
This is a sample
file that contains is
some text
is
like 123

注意: 如果文件很大,readlines() 会消耗大量内存。因此处理大文件时,建议避免使用此方案。

方法二:使用 readline() 逐行读取

读取大文件时,更有效的方法是逐行读取,而不是一次性将所有数据加载到内存中。我们可以结合 readline() 函数与文件对象使用。

readline() 每次返回文件中的下一行(末尾包含换行符)。如果到达文件末尾(EOF),它将返回一个空字符串。

示例代码如下:

# 打开文件
fileHandler = open("data.txt", "r")

while True:
    # 获取下一行
    line = fileHandler.readline()
    # 如果行为空,说明已到达文件末尾
    if not line:
        break
    print(line.strip())

# 关闭文件
fileHandler.close()

输出:

Hello
This is a sample
file that contains is
some text
is
like 123

方法三:使用上下文管理器(with open)迭代读取

打开文件后必须记得关闭。虽然当文件对象的引用被销毁时(例如函数结束),文件会自动关闭,但如果程序逻辑复杂或运行时间长,显式管理关闭操作更为安全。

我们可以使用上下文管理器(with 语句)来自动处理文件关闭等操作,即使代码块中出现异常,文件也能被正确关闭。

示例代码如下:

# 使用 with 语句自动管理文件关闭
with open("data.txt", "r") as fileHandler:
    # 直接迭代文件对象
    for line in fileHandler:
        # 每行(除最后一行外)包含换行符,使用 strip() 去除
        print(line.strip())

输出:

Hello
This is a sample
file that contains is
some text
is
like 123

在这种情况下,当控制流离开 with 代码块时,文件将自动关闭。

方法四:使用上下文管理器构建行列表

如果你需要将所有行存储到列表中进行后续处理,同时希望安全地管理文件资源,可以结合上下文管理器与列表推导或循环。

示例代码如下:

# 将文件中的所有行存入列表
listOfLines = list()

with open("data.txt", "r") as myfile:
    for line in myfile:
        listOfLines.append(line.strip())

# 查看列表内容
print(listOfLines)

输出:

['Hello', 'This is a sample', 'file that contains is', 'some text', 'is', '', 'like 123']

方法五:使用上下文管理器配合 while 循环

这种方法结合了上下文管理器的安全性与 readline() 的控制灵活性。

示例代码如下:

# 使用 with 打开文件
with open("data.txt", "r") as fileHandler:
    # 读取下一行
    line = fileHandler.readline()
    # 检查行是否为空
    while line:
        print(line.strip())
        line = fileHandler.readline()

输出:

Hello
This is a sample
file that contains is
some text
is
like 123

完整示例代码

以下是整合上述 5 种方式的完整可运行示例:

def main():
    print("****Read all lines in file using readlines() *****")
    # 方法一
    fileHandler = open("data.txt", "r")
    listOfLines = fileHandler.readlines()
    fileHandler.close()
    for line in listOfLines:
        print(line.strip())

    print("****Read file line by line and then close it manually *****")
    # 方法二
    fileHandler = open("data.txt", "r")
    while True:
        line = fileHandler.readline()
        if not line:
            break
        print(line.strip())
    fileHandler.close()

    print("****Read file line by line using with open() *****")
    # 方法三
    with open("data.txt", "r") as fileHandler:
        for line in fileHandler:
            print(line.strip())

    print("****Read file line by line using with open (list) *****")
    # 方法四
    listOfLines = list()
    with open("data.txt", "r") as myfile:
        for line in myfile:
            listOfLines.append(line.strip())
    print(listOfLines)

    print("****Read file line by line using with open() and while loop *****")
    # 方法五
    with open("data.txt", "r") as fileHandler:
        line = fileHandler.readline()
        while line:
            print(line.strip())
            line = fileHandler.readline()

if __name__ == '__main__':
    main()

完整输出:

****Read all lines in file using readlines() *****
Hello
This is a sample
file that contains is
some text
is
 
like 123
****Read file line by line and then close it manually *****
Hello
This is a sample
file that contains is
some text
is
 
like 123
****Read file line by line using with open() *****
Hello
This is a sample
file that contains is
some text
is
 
like 123
****Read file line by line using with open (list) *****
['Hello', 'This is a sample', 'file that contains is', 'some text', 'is', '', 'like 123']
****Read file line by line using with open() and while loop *****
Hello
This is a sample
file that contains is
some text
is
 
like 123
说明: 本文示例基于 Python 3 语法(如 print() 函数)。所有方法在 Python 3.x 版本中均适用,其中推荐优先使用上下文管理器(with open)相关的方式,以确保资源安全释放。