[Python] Writing Data to CSV Files: Using writerow vs. writerows

To save data in list format as a CSV file in Python, you use the writer object from the csv module.

There are two methods: writerow(), which writes one line at a time, and writerows(), which writes multiple lines at once. You can choose the appropriate one depending on your situation.

This article explains the basic writing methods and important points to prevent character encoding issues (mojibake) and blank lines.

目次

1. Writing One Line at a Time (writerow)

This method is suitable when you want to write calculation results sequentially within a loop.

Implementation Example: Recording Sales Data

import csv

# Data to write (List of lists)
# 1st row is the header, 2nd row onwards is data
sales_data = [
    ["Date", "Product", "Price"],
    ["2025-01-01", "Apple", 120],
    ["2025-01-02", "Orange", 80],
    ["2025-01-03", "Banana", 150]
]

# 1. Open the file in write mode ('w')
# newline="" is mandatory to prevent extra blank lines in Windows environments
# encoding="utf-8" prevents character corruption if non-ASCII characters are used
with open("sales_record.csv", "w", newline="", encoding="utf-8") as f:
    
    # 2. Create Writer object
    writer = csv.writer(f)
    
    # 3. Write one line at a time in a loop
    print("--- Start Writing ---")
    for row in sales_data:
        writer.writerow(row)
        print(f"Write complete: {row}")

print("--- All processing complete ---")

File Content After Execution (sales_record.csv)

Date,Product,Price
2025-01-01,Apple,120
2025-01-02,Orange,80
2025-01-03,Banana,150

2. Writing in Bulk (writerows)

If your data is already prepared as a 2D list (a list containing lists), it is more efficient to perform a bulk write using writerows() rather than using a loop.

Implementation Example: Bulk Writing

import csv

# Data to write all at once
member_list = [
    ["ID", "Name", "Department"],
    [1001, "Tanaka", "Sales"],
    [1002, "Suzuki", "Engineering"],
    [1003, "Sato", "HR"]
]

with open("members.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    
    # Pass the entire list for bulk writing
    writer.writerows(member_list)

print("Bulk write to members.csv completed.")

Explanations and Important Notes

Key Optional Arguments

  • newline="": Always specify this when opening a CSV file in write mode using Python’s open() function. If forgotten, blank lines may appear between rows, particularly in Windows environments.
  • encoding="utf-8" (or "cp932"): If the data contains Japanese (multibyte characters), you must specify the encoding to avoid garbage text.
    • While encoding="cp932" (Shift_JIS) is sometimes used when the file is intended to be opened directly in older versions of Excel in Japan, utf-8 is currently the standard recommendation.

Append Mode ('a')

If you want to add data to the end of an existing file without deleting its contents, change the mode in open() from 'w' (Overwrite) to 'a' (Append).

# Example of appending to an existing file
with open("log.csv", "a", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["2025-12-19", "Log Entry", "Success"])
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

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

目次