Home > Software engineering >  How to return each line of a text file using a recursive function?
How to return each line of a text file using a recursive function?

Time:04-02

I am trying to return each line of html.txt:

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>

My current code is this:

def line_out(file):
    if len(file) == 1:
        exit()
    for lineno, line in enumerate(file):
        if lineno == 1:
                data = line
                del file[lineno]
                return data, (line_out(file))

with open('html.txt', 'r', encoding='utf-8') as f:
    file = f.readlines()
    print(line_out(file))

My logic is: I will iterate through each line of the file by enumerating it and deleting each line I have returned/passed, then call the function with the new and smaller file until there is only one line left in that file.

When I print this function, it does not return each line. I desire:

'<!DOCTYPE html>'
'<html lang="en" dir="ltr">'
'<head>'

Any advice would be appreciated.

CodePudding user response:

Just iterate over the list of lines.

with open(filepath, ‘r’) as f:
    lines = f.readlines()
    for line_no, content in enumerate(lines):
        print(f”{line_no}: {content}”)

This will return:

1: <!DOCTYPE html>
2: <html lang="en" dir="ltr">
3: <head>

And you can of course remove the {line_no}: portion if you want just the content printed.

CodePudding user response:

You are using recursion on the list of lines returned by f.readlines(), not on the stream descriptor itself (f).

# make recursion on _open_ stream
def line_out_f(f):
    line=f.readline()
    if line=='':
        return []
    else:
        return [line] line_out_f(f)

# 'Initial call'
with open('draft.py') as f:
    lines=line_out_f(f)
# further processing
for line_no, content in enumerate(lines):
    print(f'{line_no}: {content}')
  • Related