Help us understand the problem. What is going on with this article?

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

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'])
kirinboy96
学んだこと、忘れそうなことを見返すために書いています
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした