Python - Load text file to memory and read

Introduction

The following for loop calls the file readlines method to load the file's content into memory as a list of line strings:

Demo

for line in open('main.py').readlines(): 
     print(line.upper(), end='')

Result

This readlines technique still works but is not considered the best practice and performs poorly in terms of memory usage.

It really does load the entire file into memory all at once.

It will not even work for files too big to fit into the memory space available on your computer.

Related Topic