0
0
Pythonprogramming~30 mins

Reading file data in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Reading file data
📖 Scenario: You have a text file that contains a list of fruits, one fruit per line. You want to read this file and work with the fruit names in your Python program.
🎯 Goal: Learn how to open a file, read its contents line by line, and print the list of fruits.
📋 What You'll Learn
Create a text file named fruits.txt with the exact fruit names given.
Open the file for reading using Python.
Read all lines from the file into a list.
Print the list of fruits exactly as read from the file.
💡 Why This Matters
🌍 Real World
Reading data from files is common when working with logs, configuration files, or any saved information.
💼 Career
Many programming jobs require reading and processing data from files, so this skill is essential.
Progress0 / 4 steps
1
Create the fruits.txt file with fruit names
Create a text file named fruits.txt with these exact lines, each on its own line: apple, banana, cherry, date, elderberry.
Python
Need a hint?

Use open with mode 'w' to write to the file. Use \n to add new lines.

2
Open the file fruits.txt for reading
Write code to open the file fruits.txt for reading and assign the file object to a variable called file.
Python
Need a hint?

Use open with mode 'r' to read the file.

3
Read all lines from the file into a list called fruits
Use the readlines() method on the file object to read all lines into a list called fruits.
Python
Need a hint?

The readlines() method reads all lines into a list, including newline characters.

4
Print the list fruits and close the file
Print the variable fruits to display the list of fruit names. Then close the file using the close() method.
Python
Need a hint?

Use print(fruits) to show the list. Don't forget to close the file with file.close().