Is it possible to remove columns from CSV using Ruby?

Looking at the documentation for the Ruby CSV library, I'm sure this is possible and easy.

I just need to delete the first three columns of the CSV file using Ruby, but I did not manage to run it.

+5
source share
3 answers
csv_table = CSV.read(file_path_in, :headers => true)
csv_table.delete("header_name")
csv_table.to_csv # => The new CSV in string format

Check the documentation CSV::Table: http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html

+5
source

What about:

require 'csv'

File.open("resfile.csv","w+") do |f|
  CSV.foreach("file.csv") do |row|
    f.puts(row[3..-1].join(","))
  end
end
+1
source
csv_table = CSV.read("../path/to/file.csv", :headers => true)

keep = ["x", "y", "z"]

new_csv_table = csv_table.by_col!.delete_if do |column_name,column_values|
  !keep.include? column_name
end

new_csv_table.to_csv
+1
source

All Articles