4
5

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.

Ruby CSV操作メモ

4
Last updated at Posted at 2019-01-01

概要

rubyでCSVを操作するときのメモ

ファイルから読み込み

CSV.read

CSVファイルを一度にすべて読み込む
ファイルのデータサイズが大きい時はメモリに負荷がかかるので注意!

filename = "filename.csv"
data = CSV.read(filename, headers: true)
puts data

docs

CSV.foreach

CSVファイルを1行ずつ読み込む
ファイルのデータサイズが大きい時におすすめ

filename = "filename.csv"
CSV.foreach(filename, headers: true) do |row|
  # do something
  # ex. puts row['column1']
end

docs

バイナリ or テキストから読み込み

CSV.parse

CSV形式の文字列からCSVデータを操作するときに使用する
取得したデータは1行ずつ処理できます

CSV.parse(data, headers: true) do |row|
  # do something
  # ex. puts row['column1']
end

docs

書き込み

CSV.open

w 書き込みモード
a 追加書き込みモード

filename = "filename.csv"
CSV.open(filename,'w') do |csv|
    csv << ["A", "AA", "AAA"] 
    csv << ["B", "BB", "BBB"] 
end

docs

CSV.generate

filename = "filename.csv"
date = CSV.generate do |csv|
    csv << ["A", "AA", "AAA"] 
    csv << ["B", "BB", "BBB"] 
end
File.open(filename, 'w') do |f|
  f.write(data)
end

docs

generateの引数に \uFEFFを設定してBOM付きで出力することもできます

bom = "\uFEFF"
filename = "filename.csv"
data = CSV.generate(bom) do |csv|
    csv << ["あ","い","う","え","お"] 
    csv << ["か","き","く","け","こ"] 
end
File.open(filename, 'w') do |f|
  f.write(data)
end
4
5
2

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
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?