View on GitHub

python-for-kids

Learning and exercise content on Python for Kids

Reading from a File

Like writing to a file reading from a file also can be done in many different ways. Let’s discuss few.

If a file contains only one line then this can be as simple as

filename = "C:\\temp\\myfile.txt"
f=open(filename,"r")

line = f.readline()
print(line)

f.close()

If the file is multiline then it would read only the first line.

Read a file line by line

When you have multiple lines in a file then you can take one of the approaches,

filename = "C:\\temp\\myfile.txt"
f=open(filename,"r")

for line in f:
    print(line)
f.close()

Reading file line by line using while loop

line = f.readline()
while line != '':
    print(line)
    line = f.readline()

Readine file line by line using for loop

lines = f.readlines()
for line in lines:
    print(line)

Reading everything together,

lines = f.read()
print(lines)

Next: Day 23 - Graphics with Turtle

Back to Index