0
0

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.

【CSV】ダブルクォーテーションのエスケープについてちょっとだけ調べてみた

Last updated at Posted at 2020-02-05

概要

meibo.txt
john	m	18
pau",l	m	20
alice	f	15
dabid	m	17
jasmin	f	17

このようなTSVをCSVに変換した時に以下のように本文に含まれる"の前にもう一つ"が付いたので気になって調べてみた。

meibo.csv
"john","m","18"
"pau"",l","m","20"
"alice","f","15"
"dabid","m","17"
"jasmin","f","17"

Excelで開いた結果

image1.jpg

結果

"の前に一つ"をつけてエスケープしてるらしい。
CSVの書式の定義っぽい。
今回こういうコードを書いたら自動的に"が付いてエスケープされた。

tsv_to_csv.rb
File.open('meibo2.txt', 'r:UTF-8') do |file|
  CSV.open('meibo.csv', 'w', force_quotes: true) do |csv|
    file.each do |line|
      csv << line.chomp.split("\t")
    end
  end
end

おそらくforce_quotes: trueを書いたから自動的に付いたのだろう。
試しに外して実行してみる。

tsv_to_csv.rb
File.open('meibo2.txt', 'r:UTF-8') do |file|
  CSV.open('meibo.csv', 'w') do |csv|
    file.each do |line|
      csv << line.chomp.split("\t")
    end
  end
end
meibo.csv
john,m,18
"pau"",l",m,20
alice,f,15
dabid,m,17
jasmin,f,17

あれ。"がある部分だけ"で囲まれて、エスケープ用の"がちゃんと付いた。
force_quotes: trueを書かなくても自動的に付くっぽい?
Excelで開いてみた。
image2.jpg

こっちの結果は変わらなかった。
データ形式をcsvに変えた時点で勝手にエスケープしてくれるのかも。

参照元

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?