Skip to main content

Writing Text Files: `write()` and `writelines()`

We've mastered the art of reading from files. Now it's time to look at the other side of the coin: writing data to files. This is how you can save program state, log events, generate reports, or create any text-based output you need.

Python's file objects provide two primary methods for this: .write() for individual strings and .writelines() for lists of strings.


📚 Prerequisites

You should understand how to open a file in write ('w') or append ('a') mode using the with open(...) syntax.


🎯 Article Outline: What You'll Master

In this article, you will learn:

  • file.write(): How to write a single string to a file.
  • The Newline Character (\n): Understand why you must manually add newlines.
  • file.writelines(): How to write all strings from a list to a file in one go.
  • Choosing the Right Method: When to use .write() versus .writelines().

🧠 Section 1: file.write() - Writing a Single String

The .write() method is the most fundamental way to write data. It takes a single string as an argument and writes it to the file.

Key Point: .write() does not automatically add a newline character at the end of the string. If you want your text to appear on separate lines in the file, you must explicitly add the newline character, \n.

Example: Let's create a simple report and save it to report.txt.

# write_example.py

# We open the file in 'w' mode, which will create it or overwrite it if it exists.
with open('report.txt', 'w') as f:
f.write("Sales Report\n")
f.write("============\n")
f.write("January: $1500\n")
f.write("February: $1200\n")
f.write("March: $1800\n")

print("'report.txt' has been generated.")

If you open report.txt, you will see:

Sales Report
============
January: $1500
February: $1200
March: $1800

Without the \n characters, all the text would have been jumbled together on a single line.


💻 Section 2: file.writelines() - Writing a List of Strings

What if you have your lines of text already prepared in a list? The .writelines() method is designed for this scenario. It takes an iterable (like a list or tuple) of strings and writes each string to the file.

Key Point: Just like .write(), .writelines() does not add newline characters between the strings in the list. Your strings must already have the \n characters at the end if you want them on separate lines.

Example: Let's generate a list of guest names and write them to a file.

# writelines_example.py

guests = [
"Alice\n",
"Bob\n",
"Charlie\n",
"Diana\n"
]

with open('guests.txt', 'w') as f:
f.writelines(guests)

print("'guests.txt' has been generated.")

The resulting guests.txt file will contain:

Alice
Bob
Charlie
Diana

What would happen without the \n? If our list was ["Alice", "Bob", "Charlie"], the resulting file would be AliceBobCharlie.


🛠️ Section 3: Choosing the Right Method

The choice between .write() and .writelines() depends on how your data is structured.

  • Use .write() when you are generating text on the fly, one piece at a time, or building a string incrementally. It's perfect for logging messages or writing formatted text line by line.

  • Use .writelines() when you already have a list of strings ready to go. It's more efficient than looping through the list and calling .write() for each item.

Example: A Common Pattern A frequent task is processing a list of data and writing it to a file.

# common_pattern.py

data_points = [10, 25, 15, 30, 20]

# We need to convert our numbers to strings and add newlines
lines_to_write = [f"Data point: {d}\n" for d in data_points]

with open('data_log.txt', 'w') as f:
f.writelines(lines_to_write)

print("'data_log.txt' has been generated.")

This example uses a list comprehension to prepare the list of strings before efficiently writing them all at once with .writelines().


✨ Conclusion & Key Takeaways

You now have a complete understanding of how to write text to files in Python. By combining the correct file mode ('w' or 'a') with the appropriate write method, you can save any text-based data your program generates.

Let's summarize the key takeaways:

  • file.write(string): Writes a single string to a file.
  • file.writelines(list_of_strings): Writes each string from an iterable to a file.
  • You Must Add Newlines: Neither method automatically adds newline (\n) characters. You have to include them in your strings.
  • Use 'w' to Overwrite: Opens a file for writing and erases any existing content.
  • Use 'a' to Add: Opens a file for writing and appends new data to the end.

Challenge Yourself: Create a list of your top 3 favorite movies. Write a script that opens a file named movies.txt and uses a loop and the .write() method to write each movie to the file on a new line, prefixed with its rank (e.g., "1. The Matrix\n").


➡️ Next Steps

We've covered the basics of reading and writing files. But what happens if the file you're trying to read doesn't exist, or you don't have permission to write to a directory? These situations cause errors. In our next articles, we'll dive into Exception Handling to learn how to manage these errors gracefully. But first, we'll look at the best way to ensure files are always closed with "The with Statement."

Happy writing!