【问题标题】:Ruby Reading CSV IssueRuby 阅读 CSV 问题
【发布时间】:2015-12-16 20:36:12
【问题描述】:

我正在学习 Ruby 中的 CSV 函数,虽然我可以成功地将数组写入 csv 文件,但我无法将该文件转换回数组。测试代码如下(我的应用只需要数组中的整数)

require 'rubygems'
requires 'csv'
array = [1,2,3,4,5,6,7,8]
CSV.open('array.csv', 'w') do |csv|
csv << array
puts array.inspect
new_array = Array.new
new_array = CSV.read('array.csv', converters: :numeric)
puts new_array.inspect
end

返回

[1, 2, 3, 4, 5, 6, 7, 8]
[]

array.csv 文件被写入并填充 (1,2,3,4,5,6,7,8) 但是我在读取它时只返回一个空数组。

【问题讨论】:

    标签: arrays ruby csv


    【解决方案1】:

    您的CSV.open 调用将创建文件,但其内容将被缓冲(即存储在内存中而不是写入磁盘),直到有足够的数据可以写入或您关闭文件。您要么需要手动刷新底层文件对象,要么等到它关闭。

    CSV.open('array.csv', 'w') do |csv|
      #...
    end
    new_array = CSV.read('array.csv', converters: :numeric)
    puts new_array.inspect
    

    【讨论】:

      【解决方案2】:

      对您的代码的一些评论:

      require 'rubygems'                                          #Not necessary
      requires 'csv'                                              #require instead requires
      array = [1,2,3,4,5,6,7,8]
      CSV.open('array.csv', 'w') do |csv|
        csv << array
        puts array.inspect
        new_array = Array.new                                     #Not necessary
        new_array = CSV.read('array.csv', converters: :numeric)   #Called inside writing the CSV
        puts new_array.inspect
      end
      

      您的主要问题是写作过程中的阅读。在阅读之前先关闭 CSV 文件:

      require 'csv'                                              
      array = [1,2,3,4,5,6,7,8]
      CSV.open('array.csv', 'w') do |csv|
        csv << array
        puts array.inspect
      end
      new_array = CSV.read('array.csv', converters: :numeric)   #Called inside 
      puts new_array.inspect
      

      结果:

      [1, 2, 3, 4, 5, 6, 7, 8]
      [[1, 2, 3, 4, 5, 6, 7, 8]]    
      

      您的 CSV 可能包含多行,因此结果是数组中的一个数组。它是一组行(你有一个)。每行都是一个元素数组。

      【讨论】:

        猜你喜欢
        • 2014-10-31
        • 1970-01-01
        • 1970-01-01
        • 2022-11-04
        • 2023-03-23
        • 1970-01-01
        • 1970-01-01
        • 2021-08-24
        • 1970-01-01
        相关资源
        最近更新 更多