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