From: Robert Klemme Date: 2013-04-26T04:33:05+09:00 Subject: Re: BEGINNER - Convert csv file to tsv --001a11c24cfe33150404db347ca0 Content-Type: text/plain; charset=ISO-8859-1 On Wed, Apr 24, 2013 at 11:00 AM, Hans Mackowiak wrote: > there is a lib in stdlib for parsing csv: > > require "csv" > > File.open("tmp.tsv","w") {|out| > CSV.foreach("tmp.csv") {|l| > out.write(l.join("\t")+"\n") > } > } > That's kind of inconsequent, isn't it? You use a CSV lib for reading but not for writing. That way you miss good things like quoting. I almost like tamouse's solution best - if it wasn't for the missing stream closing. To me the most straightforward would probably be: CSV.open("source.tsv", "wb", col_sep: "\t") do |cout| CSV.foreach("source.csv", col_sep: ",") do |r| cout << r end end Or, with CSV::filter: File.open("source.csv") do |cin| File.open("source.tsv", "w") do |cout| CSV.filter(cin, cout, output_col_sep:"\t") {|r| r} end end Btw. I think that CSV.filter should also work without a block and then should use it unmodified. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/ --001a11c24cfe33150404db347ca0 Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable



On Wed, Apr 24, 2013 at 11:00 AM, Hans Mackowiak = <lists@ruby-fo= rum.com> wrote:
there is a lib in stdlib for parsing csv:

require "csv"

File.open("tmp.tsv","w") {|out|
=A0 CSV.foreach("tmp.csv") {|l|
=A0 =A0 out.write(l.join("\t")+"\n")
=A0 }
}

That= 9;s kind of inconsequent, isn't it? =A0You use a CSV lib for reading bu= t not for writing. =A0That way you miss good things like quoting.

I almost like tamouse's solution b= est - if it wasn't for the missing stream closing. =A0To me the most st= raightforward would probably be:

=
CSV.open("source.tsv", "wb", col_sep: "\t") d= o |cout|
=A0 CSV.foreach("source= .csv", col_sep: ",") do |r|
=A0 =A0 cout << r
=A0 end
=
end

Or, with CSV::filter:

File.open("source.csv"= ) do |cin|
=A0 File.open("source= .tsv", "w") do |cout|
= =A0 =A0 CSV.filter(cin, cout, output_col_sep:"\t") {|r| r}
=A0 end
end

Btw. I think that CSV.filter should also work without a block= and then should use it unmodified.

Kind = regards

robert

--
remember.guy do |as, often|= as.you_can - without end
http://blog.rubybestpractice= s.com/
--001a11c24cfe33150404db347ca0--