S-JIS[2018-01-20] 変更履歴
Python3.6.4のcsvファイル読み書きのメモ。
|
csvモジュールでcsvファイルを読み書きすることが出来る。
import csv
csvファイルを読み込む例。
with open("example.csv") as file:
reader = csv.reader(file)
for row in reader: # rowは文字列(フィールド)のリスト
print(row)
1行目がヘッダー(フィールド名)であるcsvファイルを読み込む例。
string,numeric abc,123 def,456 ghi,789
with open("example_dict.csv") as file:
reader = csv.DictReader(file)
print(reader.fieldnames) # フィールド名
for row in reader: # rowはヘッダーにあるフィールド名をキーとするdict
print(row["string"], row["numeric"])
↓実行結果
['string', 'numeric'] abc 123 def 456 ghi 789
csvファイルを出力する例。
with open("write.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["abc", 123])
writer.writerow(["def", 456])
writer.writerow(["ghi", 789])
open関数でnewlineに空文字列を指定しておかないと、ファイルの改行コードが変になる。
writerowメソッドには1行分のリストを渡す。