593
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

PythonでCSVの読み書き

PythonによるCSVファイルの読み書きメモ.
3. pandasによる方法 がおすすめです.

  • Change log
2014/07/28  読み込み(Pandas)の追加.
2014/11/28  pandasを使う場合をまとめ.

1. 読み込み

Python documentation を参考にwith文を使う.

import csv

with open('some.csv', 'r') as f:
    reader = csv.reader(f)
    header = next(reader)  # ヘッダーを読み飛ばしたい時

    for row in reader:
        print row          # 1行づつ取得できる

with文を使わなくても,以下のように読み込める.

import csv

f = open('some.csv', 'r')

reader = csv.reader(f)
header = next(reader)
for row in reader:
    print row

f.close()

この場合はclose文をつける.

2. 書き込み

書き込みでもwith文を使う.

import csv

with open('some.csv', 'w') as f:
    writer = csv.writer(f, lineterminator='\n') # 改行コード(\n)を指定しておく
    writer.writerow(list)     # list(1次元配列)の場合
    writer.writerows(array2d) # 2次元配列も書き込める

読み込みと同様にwithなしでもOK.

import csv

f = open('some.csv', 'w')

writer = csv.writer(f, lineterminator='\n')
writer.writerow(list)
writer.writerows(array2d)

f.close()

3. pandasを使う方法(おすすめ)

pandasで読み込むとすっきりするし,便利な場合も多い.

import pandas as pd

df = pd.read_csv('some.csv')

print df       # show all column
print df['A']  # show 'A' column

読み込んだDataFrameは書き込みも簡単.

df.to_csv('some2.csv')

使い方は pandasでよく使う文法まとめ@okadate - Qiita などを参考に.

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
Sign upLogin
593
Help us understand the problem. What are the problem?