Python - Load file with loop

Introduction

To load a file's contents into a string all at once:

Demo

file = open('main.py', 'r')    # Read contents into a string 
print(file.read())

Result

To read file character by character:

Demo

file = open('main.py') 
while True: # from w  ww. j a  v  a 2s.  c  o  m
    char = file.read(1)         # Read by character 
    if not char: break          # Empty string means end-of-file 
    print(char) 

for char in open('main.py').read(): 
    print(char)

Result

Related Example