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
How to Click a Link in a Table Based on the Text in a Row
Detect Similar Sounding Words in Ruby
How to Pass Content to Jekyll Default Converter After Custom Conversion
Why Does the Rand() Return Always the Same Number
In Rspec, Using Let Variable Inside Before :All Block
Ruby/Rails Array of Strings to Postgresql Insert
The Program 'Rails' Is Currently Not Installed
Multipart Response in Ruby/Rack
How to Run an Excel MACro from Ruby
Nokogiri Issues with Ruby on Rails
Project Euler #3 in Ruby Solution Times Out
Compass Error for Command 'Grunt Server'
How to Use H2 as Embedded Database in Postgres-Compat Mode, from Jruby/Rails
Rails Generate Controller Gives Me Load Error
Actioncable Connected Users List