将CSV写入标准输出或文件名 [英] Write CSV to stdout or filename
问题描述
我想创建一种将CSV输出写入文件名(如果给定的话)和stdout(如果没有给出的话)的方法。
I want to make a method that writes some CSV output to a filename if given and stdout if not given.
似乎我需要处理对 CSV
的不同之处取决于它是文件还是输出到stdout,但是我真的很想将输出流 z
作为我可以写的东西,而不必考虑它是磁盘上的文件还是stdout流。
It seems like I need to treat my calls to CSV
differently depending on if it's a file or to stdout, but I'd really like to treat the output stream z
as something I can write to and not have to whether it's a file on disk or the stdout stream.
这可能吗?
以下是我的尝试和错误:
Below is my attempt and errors:
require 'csv'
require 'pathname'
require 'csv'
require 'pathname'
def write_to_csv_or_stdout foo, bar, z=nil
z = Pathname.new(z) if z
z ||= $stdout
res = [[foo, bar, "baz"]]
CSV(z) do |csv|
res.each do |row|
csv << row
end
end
end
write_to_csv_or_stdout "foo", "bar"
# foo
# bar
#=> foo,bar,baz
# write_to_csv_or_stdout "foo", "bar", "baz"
# (NoMethodError)
推荐答案
一种解决方案是不要仅使用Pathname对象,因为它不是IO对象。
One solution would be not to use only the Pathname object since it isn't an IO object.
如果打开文件,则可以像使用stdout对象一样使用它。
If you open the file then you can use it the same way as you would use the stdout object.
def some_method x, y, z=nil
puts x
puts y
z = Pathname.new(z).open if z # <== here you get an IO Object back
z ||= $stdout
res = [["foo", "bar", "baz"]]
CSV(z) do |csv|
res.each do |row|
csv << row
end
end
end
这篇关于将CSV写入标准输出或文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!