Menu
Coddy logo textTech

More Read

Lesson 8 of 12 in Coddy's File Handling in Python course.

We have seen the basic read() function, but there is more!

You can also specify how many characters you want to read,

f = open('file.txt')
s = f.read(10)

In this example, s will hold the 10 first characters from file.txt.

It's also possible to read line by line from a file using readline() or readlines() functions:

f = open('file.txt')
print(f.readline())  # prints the first line of file.txt
print(f.readline())  # prints the second line of file.txt

Or,

f = open('file.txt')
print(f.readlines())  # prints an array of all the lines in file.txt

It's also possible to simply loop over a file line by line,

f = open('file.txt')
for line in f:
	print(line)

This prints the content of file.txt line by line.

challenge icon

Challenge

Easy

Given a file named numbers.txt which contains some numbers separated by new line.

Your task is to read the file content line by line and print only the even (divisible by 2) numbers.

Note: when you read a file it returns a string, you can cast it to number using int(a), where a is the string.

Try it yourself

# Write code here

All lessons in File Handling in Python