Python - Read a file line by line with a while loop:

Description

Read a file line by line with a while loop:

Demo

f = open('main.py') 
while True: # from  w  ww  . jav  a2 s.co  m
    line = f.readline() 
    if not line: break 
    print(line.upper(), end='')

Result

This may run slower than the iterator-based for loop version, because iterators run at C language speed inside Python.

The while loop version runs Python byte code through the Python virtual machine.

The following code runs faster.

Demo

for line in open('main.py'):       # Use file iterators to read by lines 
    print(line.upper(), end='')       # Calls __next__, catches StopIteration

Result

Related Topic