• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

CSV写入标准输出或文件名

用户头像
it1352
帮助1

问题说明

我想创建一种将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)

正确答案

#1

一种解决方案是不要仅使用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
系列文章
更多 icon
同类精品
更多 icon
继续加载