Read a file line by line with a while loop:
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='')
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.
for line in open('main.py'): # Use file iterators to read by lines print(line.upper(), end='') # Calls __next__, catches StopIteration