开始使用免费开始使用

编写生成器按块加载数据(2)

在上一个练习中,您按给定的行数逐行处理了一个文件。那么如果要处理整个文件呢?

这时,使用生成器会很合适。生成器允许用户对数据进行惰性求值。 当您需要处理非常大的数据集时,惰性求值非常有用,因为它可以一次只通过 yield 一小块数据来高效地产生值,而不是一次性加载全部内容。

在本练习中,您将定义一个生成器函数 read_large_file()。它会产生一个生成器对象,每次对其调用 next() 时都会从文件中返回一行。CSV 文件 'world_dev_ind.csv' 已位于您当前的目录中,可直接使用。

请注意,当您打开一个文件连接时,得到的文件对象本身就是一个生成器!因此在实际工作中,遇到这类情况通常无需显式创建生成器对象。不过,出于教学目的,我们将通过 read_large_file() 函数让您练习如何实现它。开始吧!

本练习是课程的一部分

Python 工具箱

查看课程

练习说明

  • 在函数 read_large_file() 中,使用 readline() 方法从 file_object 读取一行,并将结果赋值给 data
  • 在函数 read_large_file() 中,yield 从文件读取的一行 data
  • 在上下文管理器中,调用您的生成器函数 read_large_file() 并传入 file,创建生成器对象 gen_file
  • 使用 next() 打印生成器对象 gen_file 产生的前三行。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Define read_large_file()
def read_large_file(file_object):
    """A generator function to read a large file lazily."""

    # Loop indefinitely until the end of the file
    while True:

        # Read a line from the file: data
        data = ____

        # Break if this is the end of the file
        if not data:
            break

        # Yield the line of data
        
        
# Open a connection to the file
with open('world_dev_ind.csv') as file:

    # Create a generator object for the file: gen_file
    gen_file = ____

    # Print the first three lines of the file
    print(____)
    print(____)
    print(____)
编辑并运行代码