Garvit Gugnani
Garvit Gugnani

Reputation: 9

Python: yield or return

So I wrote this piece of code:

def character(f):
    #Reads one character(byte by byte) from the given text file
    c = f.read(1)
    while c:
        yield c
        c = f.read(1)

I want this value to be parsed in the below function. When I run this code nothing happens. There are no errors but no output is shown too. dbc_cabin_read does reach the counter value of 30 but nothing gets printed. I think the program doesn't enter the loop.

def dbc_cabin_read(f):
    try:
        f.seek(0,0)
        ctr = 0
        for line in f.readlines():
            ctr += 1
            if ctr == 30:                 
                for c in character(f):
                    print(c, sep="", end="")
                break

    finally: 
        f.close()

In character(f), if I use return instead of yield a Type Error occurs:

Exception has occurred: TypeError 'NoneType' object is not iterable

Upvotes: 0

Views: 138

Answers (1)

Barmar
Barmar

Reputation: 780724

f.readlines() reads the entire file. If you just want to read the first 30 lines, you can call f.readline() in a loop. Then you can use your generator to continue reading from the file at that point.

for _ in range(30):
    f.readline()
for c in character(f):
    print(c, sep="", end="")

Upvotes: 3

Related Questions