Cookie
Cookie

Reputation: 434

Lazy loading file in python, using with or just using for?

Would these two solutions be the same:

def get_line(file_name):
    for line in open(file_name, "r"):
        yield line
def get_line(file_name):
    with open(file_name, "r") as f:
        yield f.readline()

We use with to auto-close a file, right? So what happens in the first example? How would one go about testing this functionality... I mean I usually mess about in the repl to understand things, but this time I get as far as verifying it's a generator but I don't know how to answer my own question given a repl.

In the case I'm working on atm I want to iterate over a large file twice, and I'll be using one of the above functions as a method on a class. Then, in two separate methods I will fully iterate through the file.

Upvotes: 0

Views: 181

Answers (2)

Frank Yellin
Frank Yellin

Reputation: 11297

If you are using a Python ≥ 3.3, you can also write:

def get_line(file_name):
    with open(file_name, "r") as f:
        yield from f

Upvotes: 1

Barmar
Barmar

Reputation: 781769

The equivalent code using with needs a loop:

def get_line(file_name):
    with open(file_name, "r") as f:
        for line in f:
            yield line

Upvotes: 1

Related Questions