0
0
Pythonprogramming~15 mins

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

Choose your learning style9 modes available
Writing file data
📖 Scenario: You are creating a simple program to save a list of favorite fruits to a text file. This is useful when you want to keep a record of your favorite items on your computer.
🎯 Goal: Build a Python program that writes a list of fruits to a file called fruits.txt. Each fruit should be on its own line in the file.
📋 What You'll Learn
Create a list called fruits with the exact values: 'apple', 'banana', 'cherry'
Create a variable called filename and set it to 'fruits.txt'
Use a with open(filename, 'w') block to open the file for writing
Inside the with block, use a for loop with variable fruit to write each fruit followed by a newline to the file
Print the message 'Data written to fruits.txt' after writing the file
💡 Why This Matters
🌍 Real World
Saving data to files is a common task for storing information like lists, logs, or settings on your computer.
💼 Career
Knowing how to write data to files is important for many programming jobs, including data processing, automation, and software development.
Progress0 / 4 steps
1
Create the list of fruits
Create a list called fruits with these exact values: 'apple', 'banana', 'cherry'.
Python
Need a hint?

Use square brackets [] to create a list and separate items with commas.

2
Set the filename variable
Create a variable called filename and set it to the string 'fruits.txt'.
Python
Need a hint?

Use an equals sign = to assign the string to the variable.

3
Write the fruits to the file
Use a with open(filename, 'w') block to open the file for writing. Inside the block, use a for loop with variable fruit to write each fruit followed by a newline character \n to the file.
Python
Need a hint?

Use with open(filename, 'w') as file: to open the file. Then loop over fruits and write each fruit plus a newline.

4
Print confirmation message
Write a print statement to display the message 'Data written to fruits.txt' after the file writing block.
Python
Need a hint?

Use print('Data written to fruits.txt') to show the message.