我有一个名为info
的数组,我想将每行添加到CSV中,但我还想将标题包含在文件的顶部。
我这样做了:
info.each do |listing|
CSV.open(csvfile, "a+", write_headers: true, headers: ["Company_Name","Website","Street_Address", "City", "State", "Zip", "Phone","Email"]) do |csv|
csv << listing
end
end
但这会产生如下情况:
这不是我想要的。
我只想在顶部有一个标题行。
我如何实现这一目标?
修改1
我实际上有另一个具有相同问题的嵌套循环,但我不能简单地将其移出循环 - 那么我怎么能解决这个问题呢?
csvs.each do |csv|
CSV.foreach(csv, headers: true) do |row|
#check for presence of valid email
if (!row['Email'].nil?) && (!row['Email'].include? "no email")
CSV.open(new_csv, "a+", write_headers: true, headers: ["Company_Name","Website","Street_Address", "City", "State", "Zip", "Phone","Email"]) do |new_csv_row|
new_csv_row << row
puts "#{row['Email']} successfully added to #{new_csv}"
end
end
end
end
答案 0 :(得分:3)
对于第一个更改循环:
CSV.open(csvfile, "a+", write_headers: true, headers: ["Company_Name","Website","Street_Address", "City", "State", "Zip", "Phone","Email"]) do |csv|
info.each do |listing|
csv << listing
end
end
第二个:
header_written = {} # memorize if header is allready written
csvs.each do |csv|
...
# alternative can be 'write_headers: !File.exist?(new_csv)'
# but this works only when this file is created here and no empty file exists
CSV.open(new_csv, "a+", write_headers: !header_written[new_csv], headers: ["Company_Name","Website","Street_Address", "City", "State", "Zip", "Phone","Email"]) do |new_csv_row|
new_csv_row << row
puts "#{row['Email']} successfully added to #{new_csv}"
end
header_written[new_csv] ||= true
编辑:我刚刚认识到new_csv
不是动态的。因此,您可以将第二个CSV.open
调用放在循环外部或使用简单标记而不是header_written[]
,以便将其更改为header_written = false|true
。