Editor

Read and Print File Contents

Beginner · Write the code · from Python File Handling: Read, Write, and Process Files

From the lesson: Python File Handling: Read, Write, and Process Files

Imagine you have a notebook where you write down important things. You open it, read what's inside, add new notes, and then close it. Python works with files the same way.

Read the lesson

You are given a simulated file f containing three fruit names, one per line. Read all lines from the file using a for loop and print each fruit name without any trailing whitespace or newlines.

The file contains:

apple
banana
cherry

Print each fruit on its own line.

import io
f = io.StringIO('apple\nbanana\ncherry\n')
# Your code here: loop through f and print each line (stripped)

More File Handling exercises

All Python exercises · 50 practice problems · File I/O & Data Formats quiz