如何将从CSV文件解析的值写入YAML文件?

时间:2013-01-24 08:16:30

标签: ruby-on-rails ruby yaml

我想将从CSV文件解析的值写入YAML文件:

home_phone = row['HomePhone']
 if home_phone.length == 10  
  puts "First Name: #{row['first_Name']} - Home Phone: #{home_phone} -  Zip Code: #{zip_code}"
  elsif home_phone.length == 11 && home_phone.start_with?('1')   
  home_phone.slice!(0)
      puts "First Name: #{row['first_Name']} - Home Phone: #{home_phone} -  Zip Code: #{zip_code}"   
  else  
      puts "First Name: #{row['first_Name']} - Home Phone: #{"0000000000"} -  Zip Code: #{zip_code}"      
  end

以上代码用于逐行打印详细信息。从代码中获得的输出是:

First Name: Douglas - Home Phone: 4252745000 -  Zip Code: 50309'

'First Name: Aya - Home Phone: 9995901339 -  Zip Code: 90210'

'First Name: Audrey - Home Phone: 0 -  Zip Code: 05667'

如何将这些值写入YAML文件?

3 个答案:

答案 0 :(得分:4)

如果您想将CSV文件转换为YAML ...

我创建了一个名为“test.csv”的文件,如下所示:

First Name,Home Phone,Zip Code
Douglas,4252745000,50309
Aya,9995901339,90210
Audrey,0,05667

使用此代码:

require 'csv'
require 'yaml'

csv = CSV.read('test.csv')
File.write('test.yaml', csv.to_yaml)
pp YAML.load_file('test.yaml')

生成:

---
- - First Name
  - Home Phone
  - Zip Code
- - Douglas
  - '4252745000'
  - '50309'
- - Aya
  - '9995901339'
  - '90210'
- - Audrey
  - '0'
  - '05667'

我从pp获得此输出,显示通过YAML-land正确往返CSV数据:

[["First Name", "Home Phone", "Zip Code"],
 ["Douglas", "4252745000", "50309"],
 ["Aya", "9995901339", "90210"],
 ["Audrey", "0", "05667"]]

这只是一个简单的解决方案,它将整个CSV文件加载到内存中。如果您处理的文件大于系统上的可用RAM,那么这不是可扩展的解决方案。 CSV支持foreach,它允许您逐行读取文件,但YAML可能会发现由于生成文件的原因而逐行编写文件很困难;它需要一个完整的散列或数组,但是你将传递它的子数组,这将导致YAML文件看起来像:

---
- - First Name
  - Home Phone
  - Zip Code
---
- - Douglas
  - '4252745000'
  - '50309'
---
- - Aya
  - '9995901339'
  - '90210'
---
- - Audrey
  - '0'
  - '05667'

使用YAML.load_file加载会导致:

[
    [0] [
        [0] "First Name",
        [1] "Home Phone",
        [2] "Zip Code"
    ]
]

换句话说,只会返回第一行。

解决方法是使用YAML.load_documents(File.open('test.yaml', 'r'))而不是load_file,它会将部件重新组合成一个数组。

答案 1 :(得分:0)

如果你的行数据是一个哈希值(它看起来像是),请尝试使用to_yaml,如下所示:

File.open(<path to your output file here>, "w") { |f| f.write(row.to_yaml) }

然后您可以这样阅读:

YAML.load_file(<path to your output file here>)

答案 2 :(得分:-1)

require 'yaml'
File.open('somefile.yaml','w') do |f|
  f.write(row['first_Name'])
  f.write(row['home_phone'])
  f.write(row['zip_code'])
end