How to remove a row from a CSV with Ruby

前端 未结 2 1852
别那么骄傲
别那么骄傲 2021-01-13 09:59

Given the following CSV file, how would you remove all rows that contain the word \'true\' in the column \'foo\'?

Date,foo,bar
2014/10/31,true,derp
2014/10/         


        
相关标签:
2条回答
  • 2021-01-13 10:24

    You might want to filter rows in a ruby manner:

    require 'csv' 
    csv = CSV.parse(File.read(@csvfile), {
      :col_sep => ",", 
      :headers => true
      }
    ).collect { |item| item[:foo] != 'true' }
    

    Hope it help.

    0 讨论(0)
  • 2021-01-13 10:25

    You should be able to use CSV::Table#delete_if, but you need to use CSV::table instead of CSV::read, because the former will give you a CSV::Table object, whereas the latter results in an Array of Arrays. Be aware that this setting will also convert the headers to symbols.

    table = CSV.table(@csvfile)
    
    table.delete_if do |row|
      row[:foo] == 'true'
    end
    
    File.open(@csvfile, 'w') do |f|
      f.write(table.to_csv)
    end
    
    0 讨论(0)
提交回复
热议问题