7

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

I simply need to delete the first three columns of a CSV file using Ruby but I haven't had any success getting it run.

1
  • 2
    What have you written? Why didn't it work? Commented Feb 7, 2012 at 23:31

4 Answers 4

10
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 CSV::Table documentation: http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html

Sign up to request clarification or add additional context in comments.

Comments

2
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

Comments

1

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 Comment

This code reads the data from "file.csv" and inserts it without the first 3 columns into "resfile.csv". The "resfile.csv" is indeed reset for every run. If you want it to have data appended just open it with "a+". The origin file "file.csv" is not changed at all.
0

I have built on a few of the questions (really liked what @fguillen did with CSV::Table) here but just made it a bit simpler to drop it into an existing project, target a file and make a quick change.

Have added byebug cause ... yes. Then also retained the headers from the original file (assuming they exist for anyone wanting to use this snippet).

The file is overwritten each time in case you want to test/tinker.

require 'csv'
require 'byebug'

in_file = './db/data/inbox/change__to_file_name.csv'
out_file = in_file + ".out"

target_col = "change_to_column_name"
 
csv_table = CSV.read(in_file, headers: true)
csv_table.delete(target_col)

CSV.open(out_file, 'w+', force_quotes: true) do |csv|
  csv << csv_table.headers
  csv_table.each_with_index do |row|
    csv << row
  end
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.