9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

StringIOを使ったCSVファイル作成

Posted at

StringIOを使用することでCSVファイルの作成を簡単に行うことができます。
以下簡単なサンプルです。

settingsに関してはこちらを参照

from typing import List
import csv
from io import StringIO


def create_csv_from_associative_array(data: List[list], **settings) -> str:
    file = StringIO()
    writer = csv.writer(file, **settings)
    writer.writerows(data)
    csv_data = file.getvalue()
    StringIO().close()

    return csv_data


settings = {
    'delimiter': ',',
    'doublequote': True,
    'lineterminator': '\r\n',
    'quotechar': '"',
    'skipinitialspace': True,
    'quoting': csv.QUOTE_MINIMAL,
    'strict': True
}

data = [['名前', '年齢', '性別'], ['tester1', 23, 'man'], ['tester2', 19, 'woman']]

cav_data = create_csv_from_associative_array(data=data, **settings)

print(cav_data)

9
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?