CSV写入标准输出或文件名
问题说明
我想创建一种将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
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcfggbi
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20 -
希伯来语的空格句子标记化错误
it1352 06-22