Python - Convert file content to uppercase

Introduction

The following code reads a file line by line, printing the uppercase version of each line, without ever explicitly reading from the file at all:

Demo

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

Result

The print uses end='' here to suppress adding a \n, because line strings already have one.

Related Topic