Read all the lines into a list


There are rare cases when you need the whole content of a file in the memory and you cannot process it line by line. In those rare cases we have several options. readlines will read the whole content into a list converting each line from the file to be an element in the list.

Beware though, if the file is too big, it might not fit in the free memory of the computer.


examples/files/read_full_file.py
filename = 'examples/files/numbers.txt'

with open(filename, 'r') as fh:
    lines = fh.readlines()   # reads all the lines into a list

print(f"number of lines: {len(lines)}")

for line in lines:
    print(line, end="")
print('------')

lines.reverse()
for line in lines:
    print(line, end="")

number of lines: 2
23 345 12345
67 189 23 17
------
67 189 23 17
23 345 12345