1
2

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.

CSVファイルの読み込みと書き込み

Last updated at Posted at 2020-08-25

CSVファイルとは、「comma separated values」の略称を指し、その名の通り値や項目をカンマ(,)で区切って書いたテキストファイル・データのこと

##書き込み

withステートメントでtest.csvというcsvファイルを作成
fieldnamesで各要素を定義

qiita.py
import csv

with open("test.csv", 'w') as csv_file:
    fieldnames = ['Name', 'Count']
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    writer.writeheader()

実行結果
test.csvの中身

Name,Count

writerowを用いて各データを追加していく

qiita.py
import csv

with open("test.csv", 'w') as csv_file:
    fieldnames = ['Name', 'Count']
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({'Name':'A', 'Count':1})
    writer.writerow({'Name': 'B', 'Count': 2})

実行結果
test.csvの中身

Name,Count
A,1
B,2

##読み込み

読むこむ際はDictreaderを使用し、forループを回す

qiita.py
import csv

with open('test.csv','r') as csv_file:
    reader = csv.DictReader(csv_file)
    for row in reader:
        print(row["Name"], row['Count'])
1
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?