【问题标题】:Ruby CSV doesn't find file headers if first line is followed by an empty one如果第一行后跟一个空行,Ruby CSV 找不到文件头
【发布时间】:2014-02-28 17:49:49
【问题描述】:

我遇到了一个奇怪的问题,即我的脚本无法处理某些 CSV 文件。问题如下,我需要访问列名(文件标题)才能正确处理文件。我一直在使用以下(测试)代码来列出标题:

CSV file = CSV.read(argument, :headers => true)
if file.headers() == nil
    puts "According to the doc : Headers will not be used"
elsif file.headers() == true
    puts "According to the doc : Headers will be used, but not read yet"
else
    puts "Headers were read, this is an array : #{file.headers.to_s}"
end

现在,应用于第一个 csv:

key,fr
edit,Éditer
close,Fermer

我明白了:

Headers were read, this is an array : ["key", "fr"]

但是,如果我知道在标题和内容本身之间添加一个空行,就像这样:

key,fr

edit,Éditer
close,Fermer

它不再起作用了:

Headers were read, this is an array : []

这让我很困惑。这是预期的行为吗?我能做些什么吗?我一直在阅读 ruby​​ CSV 文档,但找不到任何东西。 会不会是一些我不知道的 csv 文件规格? 在 ruby​​ 1.9.3 和 2.1.1 上测试

【问题讨论】:

  • 你在期待什么?如果您得到这样的文件,则它不是有效的 CSV 文件。
  • 如果您读取的文件源于用户输入,您可以尝试通过在将空行传递给 CSV 之前拒绝空行来预测此类简单错误。

标签: ruby csv


【解决方案1】:

在读取 CSV 文件时添加选项:skip_blanks => true

file = CSV.read(path, :headers => true,:skip_blanks => true)

这个选项:skip_blanks => true,如果你有任何这样的空行,将跳过所有这样的空行,你会得到正常的输出。

这是我的尝试:

require 'csv'

content = <<_
key,fr

edit,Éditer
close,Fermer
_

File.write('test',content)

file = CSV.read('test', :headers => true,:skip_blanks => true)
if file.headers() == nil
    puts "According to the doc : Headers will not be used"
elsif file.headers() == true
    puts "According to the doc : Headers will be used, but not read yet"
else
    puts "Headers were read, this is an array : #{file.headers.to_s}"
end
# >> Headers were read, this is an array : ["key", "fr"]

按照你说的正确工作,我也同意你的看法,如下:

require 'csv'

content = <<_
key,fr
edit,Éditer
close,Fermer
_

File.write('test',content)

file = CSV.read('test', :headers => true)
file.headers # => ["key", "fr"]
file.to_a # => [["key", "fr"], ["edit", "Éditer"], ["close", "Fermer"]]

当您设置:headers =&gt; true,CSV 数据的第一行时,您将被视为标题。考虑到这个定义,上述进展顺利。但下面的一个矛盾:

require 'csv'

File.write('test',content)

file = CSV.read('test', :headers => true)
file.headers # => ["key", "fr"]
file.to_a # => [["key", "fr"], ["edit", "Éditer"], ["close", "Fermer"]]

content = <<_
key,fr

edit,Éditer
close,Fermer
_

File.write('test1',content)

file = CSV.read('test1', :headers => true)
file.headers # => []  # <~~~~~~~~~~~ Is this a bug ?
file.to_a # => [[], [], ["edit", "Éditer"], ["close", "Fermer"]]

file.headers 给出了一个空数组[],可以看到在file.to_a 的输出的0th 索引中也是一个空数组([])。但这似乎是一个错误。因此我提出了issue

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多