522
590

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 5 years have passed since last update.

PythonでCSVの読み書き

Last updated at Posted at 2013-11-29

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 などを参考に.

522
590
1

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
522
590

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?