我可以使用CSV.foreach删除CSV中的行吗?

时间:2016-04-15 23:05:10

标签: ruby csv delete-row

我需要在符合条件的情况下从CSV中删除行,是否可以使用CSV.foreach从CSV文件中删除行?

这是我的代码片段

require 'csv'

path = 'C:\Users\ALilland\Documents\macros\automated-jobs-change-orders-report\jobs-and-change-orders.csv'

CSV.foreach(path, :encoding => 'windows-1251:utf-8') do |row|
  sp = row[1]
  next if sp == 'BD' || sp == 'RR' || sp == 'FU' || sp == 'JH' || sp == 'MN' ||
          sp == 'DR' || sp == 'MT' || sp == 'MM' || sp == 'GS' || sp == 'DM' ||
          sp == 'JN'

  row[1].delete # need something like this
end

1 个答案:

答案 0 :(得分:0)

CSV.foreach是只读的。如果你想写入csv文件,你需要像

这样的东西
CSV.open(path+"~", "wb") do |out_csv|
  CSV.foreach(path) do |in_csv|
    out << in_csv if row_should_be_included?(in_csv)
  end
end

File.delete(path)
File.rename(path+"~",path)