1
1

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 1 year has passed since last update.

PythonによるCSVの読み書き(備忘)

Posted at

ほぼほぼフルオプション指定のCSV/TSV読み書き

import csv

# CSV/TSV出力サンプル
# - ヘッダーあり
# - 最低限のクォート処理
# - null値の表現あり(null)
header = ['a','b','c','d']
with open('sample.csv', 'w') as f:
    w = csv.DictWriter(f, 
        header,             # ヘッダー指定
        dialect='excel',    # dialectはExcelを指定
        delimiter="\t",     # 区切り文字
        restval="(null)",   # 指定がなければ空白
        quotechar='@',      # データに改行があるときの囲み文字
        quoting=csv.QUOTE_MINIMAL   # 最低限の囲み文字
    )
    w.writeheader()
    w.writerow({
        'a': 123,
        'b': 456,
        'c': 'abc\ndef\n\"abc@def\tghi\"\n'
    })

    # 出力
    # a	b	c	d
    # 123	456	@abc
    # def
    # "abc@@def	ghi"
    # @	
    

# CSV/TSV読み込み
# - ヘッダーあり
# - 最低限のクォート処理
# - 囲み文字指定(@)
with open('sample.csv', 'r') as f:
    r = csv.DictReader(f, 
        dialect='excel', 
        delimiter="\t", 
        quotechar='@',
        quoting=csv.QUOTE_MINIMAL)

    for row in r:
        print(row)
    
    # 出力
    # {'a': '123', 'b': '456', 'c': 'abc\ndef\n"abc@def\tghi"\n', 'd': ''}

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?