開始使用免費開始

撰寫產生器以分批載入資料(2)

在前一個練習中,你針對指定的行數逐行處理檔案。不過,如果你想要對整個檔案都這樣做呢?

這種情況下,使用「產生器(generators)」會很實用。產生器可讓你以「延遲求值(lazy evaluation)」的方式處理資料。 當你面對非常大的資料集時,延遲求值特別有用,因為它一次只「yield」一小塊資料,而不是一次載入全部,讓產生值的方式更有效率。

在這個練習中,你會定義一個產生器函式 read_large_file()。它會回傳一個產生器物件,每次對它呼叫 next() 時,就會從檔案中傳回一行。名為 'world_dev_ind.csv' 的 CSV 檔已經放在你目前的目錄中,可供使用。

請注意,當你開啟一個檔案連線時,得到的檔案物件本身就已經是產生器了!所以在真實情境中,像這樣的案例通常不需要你另外手動建立產生器物件。不過基於教學目的,我們要你透過 read_large_file() 來練習如何自己建立。開始動手吧!

本練習屬於課程

Python 工具箱

檢視課程

練習說明

  • 在函式 read_large_file() 中,使用 readline() 方法從 file_object 讀取一行,並將結果指定給 data
  • 在函式 read_large_file() 中,對從檔案讀到的這一行 data 使用 yield
  • 在情境管理器中,呼叫你的產生器函式 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(____)
編輯並執行程式碼