Writing to Text Files in Python: Differences Between write() and writelines(), and Handling Newlines

When saving calculation results or log data to a file in Python, you open the file in “write mode” using the built-in function open() and use methods to write the data. There are two methods for writing: write(), which writes a single string, and writelines(), which writes a sequence like a list all at once.

This article explains the basic usage of each and how to handle “newline codes,” which is a common point of confusion.


目次

1. write(): Writing a String

The write() method writes the single string passed as an argument to the file.

Note: Unlike the print() function, write() does not automatically add a newline (\n) at the end. If you need a newline, you must explicitly include \n in the string.

Specific Usage Example

Here is an example of writing daily report header information to a file.

file_path = "daily_report.txt"
report_content = "Date: 2025-12-05\nAuthor: Yamada\nTask: Data Analysis\n"

# Open in 'w' mode and write (Create new if not exists, overwrite if exists)
with open(file_path, "w", encoding="utf-8") as f:
    # Write string at once
    f.write(report_content)
    
    # Write additional content (Don't forget the newline)
    f.write("--------------------\n")
    f.write("Progress: 80%\n")

print(f"Wrote to {file_path}.")

File created after execution (daily_report.txt):

Date: 2025-12-05
Author: Yamada
Task: Data Analysis
--------------------
Progress: 80%

2. writelines(): Writing a List at Once

The writelines() method receives a list of strings (or an iterable like a tuple) and writes them to the file in order.

Important Note: Although the method name implies “lines,” it also does not automatically add newlines. If the newline code is not included at the end of each element in the list, all strings will be written connected on a single line.

Specific Usage Example: Saving a Product List

Let’s consider saving a list of product names to a file.

product_list = ["Desktop PC", "Monitor", "Keyboard", "Mouse"]
file_path_list = "products.txt"

with open(file_path_list, "w", encoding="utf-8") as f:
    # Bad Example: writelines as is does not add newlines
    # f.writelines(product_list)
    # -> Desktop PCMonitorKeyboardMouse (All connected)

    # Good Example: Add newline code to the end of each element before writing
    # Create a list with newlines using list comprehension
    lines_with_break = [f"{item}\n" for item in product_list]
    
    f.writelines(lines_with_break)

print(f"Wrote list to {file_path_list}.")

File created after execution (products.txt):

Desktop PC
Monitor
Keyboard
Mouse

Using list comprehension [f"{item}\n" for item in product_list] allows you to concisely create a list with newlines.


Writing in Append Mode (a)

If you set the open() mode to 'w' (Write), all existing file content is erased and overwritten. To add data to the end while keeping existing content, use 'a' (Append) mode.

log_file = "app.log"

# Open in 'a' mode (Append)
with open(log_file, "a", encoding="utf-8") as f:
    f.write("2025-12-05 10:00:00 - Process started\n")
    f.write("2025-12-05 10:00:05 - Process completed\n")

print(" appended to log.")

Summary

  • write(str): Writes a single string. Newlines are not automatically added.
  • writelines(list): Writes a list of strings by concatenating them. Newlines are not automatically added between elements.
  • If newlines are needed, you must explicitly include \n.
  • Use 'w' mode for overwriting and 'a' mode for appending.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次