Practice Question 28
In this question, we will learn how to write a function that takes the content of two separate files and joins them into a third file. We will use the Parallel List Processing method, which is the most reliable way for students to handle this.
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
To merge files line by line, we treat each file as a list of lines:
-
Open the Sources: Open
file1.txtandfile2.txtin read mode. -
Open the Destination: Open
combined.txtin write mode. -
The “Transfer” Loop: 1. Read all lines from
file1and write them tocombined. 2. Read all lines fromfile2and write them tocombined. -
Alternative “Interleave” logic: If you want Line 1 from File A then Line 1 from File B, you would use a single loop with an index. (The code below follows the simpler, standard “Concatenate” merge usually asked in exams).
Let’s Code as per the above logic :
def mergeTwoFiles():
# Step 1: Open the destination file
f_out = open("combined.txt", "w")
# Step 2: Read and write content from the first file
f1 = open("file1.txt", "r")
f_out.write(f1.read())
# Adding a newline to ensure the second file starts on a new line
f_out.write("\n")
f1.close()
# Step 3: Read and write content from the second file
f2 = open("file2.txt", "r")
f_out.write(f2.read())
f2.close()
f_out.close()
print("Files merged successfully into combined.txt!")
# To call the function:
mergeTwoFiles()
Important Notes for Students
As a teacher, I want you to focus on these three key points so you don’t lose marks:
-
Handling Newlines: I added
f_out.write("\n")between the two files. Without this, if the first file doesn’t end with a newline, the first line of the second file will be joined to the end of the last line of the first file. -
Mode Matters: Notice that
combined.txtis opened in"w"mode. This ensures that every time you run the function, it creates a fresh merged file. If you wanted to keep adding to it, you would use"a"(append) mode. -
Large Files: For very large files, we wouldn’t use
.read()as it might consume too much RAM. We would use afor line in f1:loop to transfer data piece by piece.
Teacher’s Secret Tip for Exams:
If the examiner asks to merge them alternatively (Line 1 of A, then Line 1 of B, then Line 2 of A…), you would use readlines() for both and a loop like for i in range(len(list1)):.
Want to practice more? If you found this helpful, I have compiled a full list of 30 practice problems just like this one. Each question focuses on a different logic to help you become a pro at File Handling.
Click here to view the full 30-Question Practice Set