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

PythonでCSVの読み書き

More than 3 years have passed since last update.

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

okadate
数値モデルを使った沿岸域の生態系に関する研究をしています.計算結果の可視化・解析にPythonを使うので,メモ・勉強用の内容を投稿します.
http://okadate.github.io
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
ユーザーは見つかりませんでした