In this tutorial, we will learn how to write a letter in Python. This is a basic task that is helpful for understanding basic file operations and formatting concepts in Python. By the end of this tutorial, you will know how to create, format, and save a text file containing a letter using Python.
Step 1: Set Up The Letter Template
First, let’s create a function that will generate the letter template. A letter typically has a recipient, sender, message, and date. So we will create a function that has these parameters and returns the formatted letter as a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
def create_letter_template(recipient, sender, date, message): letter_template = f""" {date} Dear {recipient}, {message} Sincerely, {sender} """ return letter_template |
Step 2: Define The Letter Content
Now let’s define a letter’s content by providing values for the recipient, sender, date, and message.
1 2 3 4 |
recipient = "John Doe" sender = "Jane Smith" date = "August 1, 2021" message = "I hope you're enjoying your summer vacation!" |
Step 3: Write The Letter To A File
Now that we’ve set up the letter template and defined the letter content, we can write the letter to a text file. To do this, we will use the open function with the “w” (write) mode, which creates a new file if it doesn’t exist, or overwrites an existing file with the same name.
1 2 3 |
def write_letter_to_file(letter, file_name): with open(file_name, 'w') as file: file.write(letter) |
Call this function by providing the letter template and a file name.
1 2 3 |
file_name = "letter.txt" letter = create_letter_template(recipient, sender, date, message) write_letter_to_file(letter, file_name) |
Now, you will have a text file called “letter.txt” containing the formatted letter.
Full Python Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
def create_letter_template(recipient, sender, date, message): letter_template = f""" {date} Dear {recipient}, {message} Sincerely, {sender} """ return letter_template def write_letter_to_file(letter, file_name): with open(file_name, 'w') as file: file.write(letter) recipient = "John Doe" sender = "Jane Smith" date = "August 1, 2021" message = "I hope you're enjoying your summer vacation!" file_name = "letter.txt" letter = create_letter_template(recipient, sender, date, message) write_letter_to_file(letter, file_name) |
Output Text File: letter.txt
August 1, 2021 Dear John Doe, I hope you're enjoying your summer vacation! Sincerely, Jane Smith
Conclusion
In this tutorial, we learned how to write a letter in Python by using a formatted string template and basic file operations. This simple program is a great starting point for learning fundamental concepts in Python related to creating text files and formatting content. Next, you might wish to explore more advanced file processing techniques or learn how to generate PDF or DOCX files to customize your output file format.