Python Lab · Experiment 31
Merge two files into a third file
PythonWeek 7JNTUH R22 · CS206ES
Aim
To write a Python program that reads the names of two text files and a third file from the user, and writes the contents of the first file followed by the contents of the second file into the third file.
Algorithm
- Read the names of the first file, the second file and the output file.
- Open the first file for reading and read all its text. If it does not exist, print an error and stop.
- Do the same for the second file.
- If the first file's text does not end with a newline, add one, so the second file starts on a new line.
- Open the output file in write mode (
"w") and write the first file's text, then the second file's text. - Print a message saying which files were merged into which file.
Program
def read_file(name):
with open(name, "r") as f:
return f.read()
def merge_files(first, second, output):
text1 = read_file(first)
text2 = read_file(second)
if text1 and not text1.endswith("\n"):
text1 += "\n"
with open(output, "w") as f:
f.write(text1)
f.write(text2)
first = input("Enter first file name: ")
second = input("Enter second file name: ")
output = input("Enter output file name: ")
try:
merge_files(first, second, output)
print(f"{first} and {second} merged into {output}")
except FileNotFoundError as e:
print("Error: file not found:", e.filename)Output
Both files exist
Python was created by Guido van Rossum.
It was first released in 1991.Python is used for web apps, data science and automation.
Its code is easy to read.$ python3 prog.py
Enter first file name: part1.txt
Enter second file name: part2.txt
Enter output file name: merged.txt
part1.txt and part2.txt merged into merged.txt
$ cat merged.txt
Python was created by Guido van Rossum.
It was first released in 1991.
Python is used for web apps, data science and automation.
Its code is easy to read.The second file is missing
Python was created by Guido van Rossum.
It was first released in 1991.Enter first file name: part1.txt
Enter second file name: notes.txt
Enter output file name: merged.txt
Error: file not found: notes.txtRecorded by running this exact program. Typed input appears after each prompt.
How it works
with open(...) as f: closes the file automatically at the end of the block, even if an error happens inside it.
The output file is opened in "w" mode, which creates it if it does not exist and empties it if it does. To add to an existing file without losing its contents, use "a" (append) mode.
Both input files are read before the output file is opened. So if the second file is missing, as in the second run, the program stops with a message and does not create a half-written merged.txt.
e.filename is the name of the file that could not be opened, which makes the error message clear.
Common mistakes
Opening the output file in
"r"mode. A file opened for reading cannot be written to, and"r"fails if the file does not exist yet. Use"w"or"a".Using the same name for an input file and the output file. Opening it in
"w"mode empties it before it is read, so its contents are lost.Forgetting that the last line of the first file may not end with a newline. Then the last line of file 1 and the first line of file 2 are joined into one line.
Opening files without
withand forgettingclose(). Written data may not be saved to the disk until the file is closed.
Viva questions
Try to answer each one aloud before you open it.
What is the difference between the "w" and "a" modes of open()?
"w"creates the file or empties an existing one and writes from the start."a"opens the file for writing at the end, keeping what is already in it.What is the advantage of using with to open a file?
The file is closed automatically when the
withblock ends, even if an exception happens inside it.What is the difference between read(), readline() and readlines()?
read()returns the whole file as one string,readline()returns the next single line, andreadlines()returns a list of all the lines.What happens if you open a file that does not exist in "r" mode?
Python raises
FileNotFoundError.How else could you merge the two files without reading each one completely into memory?
Open the output file, then loop over each input file line by line (
for line in f:) and write each line. This works even for very large files.