[Solved] How to recursively read all characters in a list? [closed]


One way to think about recursion is to try and solve only a small piece of the problem, and then imagine that recursive call ‘magically’ solves the rest of the problem. Importantly, you have to consider what happens when the rest of the problem is trivial to solve; this is called the base case.

In this case, the small piece we can solve in one recursive call is reading a single character (byte). The base case occurs if there were no characters left in the file; when this happens, you append nothing to the list and just return what you already have built up.

This idea can be implemented as follows.

f = open('test_file.txt', 'r')
char_list = []

def read_rec(fh, chars):
    curChar = fh.read(1)
    if curChar: #returns False at the end of the file
        chars.append(curChar) #append to chars
        return read_rec(fh, chars) #recursively read the rest of the file
    return chars

print read_rec(f, char_list)

Output

['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 'G', 'a', 'r', 'r', 'e', 't', 't', '\n']

2

solved How to recursively read all characters in a list? [closed]