2015-09-19 31 views
0

我在Ruby中学习CSV函数,虽然我可以成功将数组写入csv文件,但我无法将该文件转换回数组。测试代码如下(我的应用程序只需要在数组中的整数)Ruby Reading 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)但是当我读它时,我只是返回一个空数组。

回答

4

在你的代码的一些言论:

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可能包含多行,所以结果是在一个数组的数组。这是一个行数组(你有一个)。每行是一组元素。

2

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

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