way to read text file line by line today is to not read it at all--insteadallow the for loop to automatically call __next__ to advance to the next line on each iteration the file object' iterator will do the work of automatically loading lines as you go the followingfor examplereads file line by lineprinting the uppercase version of each line along the waywithout ever explicitly reading from the file at allfor line in open('script py')print(line upper()end=''import sys print(sys pathx print( * use file iterators to read by lines calls __next__catches stopiteration notice that the print uses end='here to suppress adding \nbecause line strings already have one (without thisour output would be double-spacedin xa trailing comma works the same as the endthis is considered the best way to read text files line by line todayfor three reasonsit' the simplest to codemight be the quickest to runand is the best in terms of memory usage the olderoriginal way to achieve the same effect with for loop is to call the file readlines method to load the file' content into memory as list of line stringsfor line in open('script py'readlines()print(line upper()end=''import sys print(sys pathx print( * this readlines technique still works but is not considered the best practice today and performs poorly in terms of memory usage in factbecause this version really does load the entire file into memory all at onceit will not even work for files too big to fit into the memory space available on your computer by contrastbecause it reads one line at timethe iterator-based version is immune to such memory-explosion issues the iterator version might run quicker toothough this can vary per release as mentioned in the prior sidebar"why you will carefile scannerson page it' also possible to read file line by line with while loopf open('script py'while trueline readline(if not linebreak print(line upper()end=''same output howeverthis may run slower than the iterator-based for loop versionbecause iterators run at language speed inside pythonwhereas the while loop version runs python byte code through the python virtual machine anytime we trade python code for iterations and comprehensions