0
0
Pythonprogramming~30 mins

Handling multiple resources in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling multiple resources
📖 Scenario: Imagine you are working with two text files that contain important information. You need to open both files, read their contents, and then close them properly to avoid any problems.
🎯 Goal: You will write a Python program that opens two files at the same time, reads their contents, and prints the combined text. This will teach you how to handle multiple resources safely and efficiently.
📋 What You'll Learn
Create two text files named file1.txt and file2.txt with some sample text.
Open both files at the same time using a single with statement.
Read the contents of both files.
Print the combined contents of the two files.
💡 Why This Matters
🌍 Real World
Opening and reading multiple files at once is common when you need to combine data from different sources, like logs or reports.
💼 Career
Many programming jobs require managing multiple resources safely, such as files, network connections, or databases, to avoid errors and data loss.
Progress0 / 4 steps
1
Create two text files with sample content
Create two text files named file1.txt and file2.txt with the exact contents: file1.txt should contain the text "Hello from file 1!" and file2.txt should contain the text "Hello from file 2!". Use Python code to write these files.
Python
Need a hint?

Use open(filename, 'w') to create and write to a file.

2
Set up a variable to hold combined content
Create a variable called combined_text and set it to an empty string ''. This will hold the text from both files.
Python
Need a hint?

Just write combined_text = '' to start with an empty string.

3
Open both files together and read their contents
Use a single with statement to open file1.txt as f1 and file2.txt as f2 in read mode. Then read the contents of both files using f1.read() and f2.read(), and add them to the combined_text variable.
Python
Need a hint?

Use with open('file1.txt', 'r') as f1, open('file2.txt', 'r') as f2: to open both files at once.

4
Print the combined contents
Write a print statement to display the value of the combined_text variable.
Python
Need a hint?

Use print(combined_text) to show the combined text.