0
0
Pythonprogramming~15 mins

Reading files line by line in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Reading files line by line
📖 Scenario: You have a text file named fruits.txt that contains a list of fruit names, one on each line. You want to read this file line by line to process the fruit names.
🎯 Goal: Build a Python program that reads the fruits.txt file line by line and stores each fruit name in a list called fruit_list. Then print the list.
📋 What You'll Learn
Create a variable called filename with the value 'fruits.txt'.
Create an empty list called fruit_list to store fruit names.
Use a with open(filename, 'r') block to open the file for reading.
Use a for loop with the variable line to read the file line by line.
Inside the loop, use line.strip() to remove extra spaces and newlines.
Append each stripped line to fruit_list.
Print the fruit_list after reading all lines.
💡 Why This Matters
🌍 Real World
Reading files line by line is useful when you want to process large text files without loading everything into memory at once, like reading logs or data files.
💼 Career
Many programming jobs require reading and processing files efficiently, especially in data analysis, web development, and automation tasks.
Progress0 / 4 steps
1
Set the filename and create an empty list
Create a variable called filename and set it to 'fruits.txt'. Then create an empty list called fruit_list.
Python
Need a hint?

Use filename = 'fruits.txt' to store the file name and fruit_list = [] to create an empty list.

2
Open the file for reading
Add a with open(filename, 'r') block to open the file for reading.
Python
Need a hint?

Use with open(filename, 'r') as file: to open the file safely for reading.

3
Read the file line by line and add to list
Inside the with block, use a for loop with the variable line to read the file line by line. Inside the loop, use line.strip() to remove spaces and newlines, then append the result to fruit_list.
Python
Need a hint?

Use for line in file: to read each line, then fruit_list.append(line.strip()) to add the cleaned line to the list.

4
Print the list of fruits
After the with block, write a print(fruit_list) statement to display the list of fruits.
Python
Need a hint?

Use print(fruit_list) to show the list after reading the file.