Skip to content

CSV#

読込み
import csv

with open('sample.csv','r', newline='') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in spamreader:
        print(', '.join(row))
書き込み
import csv

sample_list = [
    [1,2,3],
    [test1,test2,test3],
    [contents1,contents2,contents3]
    ]

with open("csvfile.csv", "w", newline="") as f:
    writer = csv.writer(f)
    for row in sample_list:
        writer.writerow(row)
行ごとにデータ取得
with open("csvfile.csv", "w", newline="") as f:
    csv_file = csv.reader(f)
    header = next(f)
    print(header)
    for row in f:
        print(row)

Info

next()関数でheader をスキップして行を読み込めます。

辞書型で読み込む
with open("csvfile.csv", "r", newline="") as f:
    csv_file = csv.DictReader(f)
    for dic in csv_file:
    #dic["column_name"] or dic.get("column_name")でカラム名を指定してデータにアクセス可能
        print(dic)
辞書型で書き込む
d1 = {'a': 1, 'b': 2, 'c': 3}
d2 = {'a': 4, 'b': 5, 'c': 6}

with open('./sample.csv', 'w') as f:
    writer = csv.DictWriter(f, ['a', 'b', 'c'])
    writer.writeheader()
    writer.writerow(d1)
    writer.writerow(d2)

Info

キーが存在しない辞書を書き込むとその要素はスキップされ、欠損値となる。

keyをヘッダーにvalueをwriterows()で書き込み
d1 = {'a': 1, 'b': 2, 'c': 3}
d2 = {'a': 4, 'b': 5, 'c': 6}

with open('./sample.csv', 'w') as f:
    writer = csv.DictWriter(f, ['a', 'b', 'c'])
    writer.writeheader()
    writer.writerows([d1, d2]) # 辞書のリストとして渡す