🖥

#Ruby で SJIS のCSVファイルを書き込む、読み込む

2020/01/26に公開

encodingフラグを使って色々とやる
stringに対しての直接のencodeは必要なさそう

File.write('tmp/sjis.csv', "あ,い,う\nえ,お,か", encoding: Encoding::SJIS)
#  => 17

File.read('tmp/sjis.csv', encoding: Encoding::SJIS)
# => "あ,い,う\nえ,お,か"

CSV.read('tmp/sjis.csv', encoding: Encoding::SJIS)
# => [["あ", "い", "う"], ["え", "お", "か"]]


CSV.open('tmp/sjis2.csv', 'w', encoding: Encoding::SJIS) do |row|
  row << ['か', 'き', 'く']
  row << ['け', 'こ', 'さ']
end
# => <#CSV io_type:File io_path:"tmp/sjis2.csv" encoding:UTF-8 lineno:2 col_sep:"," row_sep:"\n" quote_char:"\"">

File.read('tmp/sjis2.csv', encoding: Encoding::SJIS)
# => "か,き,く\nけ,こ,さ\n"

CSV.read('tmp/sjis2.csv', encoding: Encoding::SJIS)
# => [["か", "き", "く"], ["け", "こ", "さ"]]

Original by Github issue

https://github.com/YumaInaura/YumaInaura/issues/2963

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2020-01-26

Discussion