How to Remove a Row from a CSV with Ruby

How to remove a row from a CSV with Ruby

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

Ruby - Delete rows in csv file using enumerator CSV.open

If you want to skip the first four rows plus the header, this are some options.

Get pure array:

new_csv = CSV.read(filename)[5..]

or keep the csv object

new_csv = []
CSV.open(filename, headers:true) do |csv|
csv.each_with_index do |row, i|
new_csv << row if i > 3
end
end

or using Enumerable#each_with_object:

csv = CSV.open(filename, headers:true)
new_csv = csv.each_with_index.with_object([]) do |(row, i), ary|
ary << row if i > 3
end

Remove row of a CSV file based on the index by iterating over the rows

The thing you thought of is not complicated, just rewrite the file.

File.open(@filepath, 'w') { |f| f.puts(@file) }

How to delete the entire row in the csv file in ruby 1.9.2

You can fetch all the rows at once by using:

arr_of_arrs = CSV.read("path/to/file.csv")

And then you can use arr_of_arrs.drop(1) to remove header.
Or you can use arr_of_arrs.each_with_index to skip the first row (header), like this:

arr_of_arrs.each_with_index do |e, i|
next if i == 0

#process each row here
end

Ruby csv - delete row if column is empty

Almost there. The table method changes the headers to symbols, and delete_if takes a block, the same way as each and 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

how to delete a row of csv file using Ruby?

Something like :

source=File::open("source","r")
dest=File::open("dest","w")
source.each_line do |line|
next if f.lineno == 1
dest.write(line)
end
source.close
dest.close


Related Topics



Leave a reply



Submit