尝试使用Ruby从csv文件中删除行而没有成功。
我如何判断所有行,列" newprice"是空的,应该删除吗?
require 'csv'
guests = CSV.table('new.csv', headers:true)
guests.each do |guest_row|
p guests.to_s
end
price = CSV.foreach('new.csv', headers:true) do |row|
puts row['newprice']
end
guests.delete_if('newprice' = '')
File.open('new_output.csv', 'w') do |f|
f.write(guests.to_csv)
end
谢谢!
答案 0 :(得分:1)
几乎就在那里。 table
方法将标题更改为符号,delete_if
采用块,与each
和open
相同。
require 'csv'
guests = CSV.table('test.csv', headers:true)
guests.each do |guest_row|
p guest_row.to_s
end
guests.delete_if do |row|
row[:newprice].nil?
end
File.open('test1.csv', 'w') do |f|
f.write(guests.to_csv)
end