Python3超基礎(3)

CSV処理

CSV処理は専用のcsvモジュールがあるので、それを使うと便利

  • CSV読み込み
import csv

try :
    fr = open("readcsv.csv", "r")
except FileNotFoundError:
    print("file not found")
finally:
    print("complete")

reader = csv.reader(fr)
# 1行目を読み飛ばす(例えばヘッダ)
header = next(reader)
for row in reader:
    print(row)
    # ['1', '2', '3']
    # ['4', '5', '6']
fr.close()
  • CSV書き込み
import csv

try :
    fr = open("writecsv.csv", "w")
except FileNotFoundError:
    print("file not found")
finally:
    print("complete")

writer = csv.writer(fr, lineterminator='\n')
write_list = ["dog", "cat", "rat"]
writer.writerows(write_list)
# ['d', 'o', 'g']
# ['c', 'a', 't']
# ['r', 'a', 't']
fr.close()
-->