Open In App

Python Program to Merge Mails

Last Updated : 28 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to merge mails with Python

Python Program to Merge Mails

To merge two or more mail files in Python, the below following steps have to be followed:

To execute the program, firstly we require two .txt files ‘mail1.txt‘ and ‘mail2.txt’ where both of the .txt files will contain some content on it.

Python3




with open('mail1.txt', 'r') as f1, open('mail2.txt', 'r') as f2:
   # Read the contents of each file using read() method
   mail1_content = f1.read()
   mail2_content = f2.read()
   # Combining the contents of both mail files with a delimiter
   merged_mail = mail1_content + '\n---\n' + mail2_content
# Write the merged content to a new file
with open('new_mail.txt', 'w') as f:
   f.write(merged_mail)


Explanation:

This code first opens both mail files in read mode using the built-in open() function of python. Then it read these files one by one. The variable named ‘mail1_content’ will hold the content of the ‘mail1.txt’ and another variable named ‘mail2_content’ will store the content of the ‘mail2.txt‘ file. Once the content of both of these files is stored then it will combine the contents of both the mail file into a single variable named ‘merged_mail‘ with a delimiter such as “—” using string concatenation.

Finally, it will open another file in write mode and will write the content to a new file named ‘new_mail.txt’ using the python built-in write() method.

Output:

output


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads