如何从使用Ruby的CSV中删除一行 [英] How to remove a row from a CSV with Ruby
问题描述
给定以下CSV文件,如何删除列foo中包含true一词的所有行?
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/31,false,derp
我有一个工作的解决方案,但它需要一个辅助CSV对象 csv_no_foo
@csv = CSV.read(@csvfile, headers: true) #http://bit.ly/1mSlqfA
@headers = CSV.open(@csvfile,'r', :headers => true).read.headers
# Make a new CSV
@csv_no_foo = CSV.new(@headers)
@csv.each do |row|
# puts row[5]
if row[@headersHash['foo']] == 'false'
@csv_no_foo.add_row(row)
else
puts "not pushing row #{row}"
end
end
,我只是从CSV中删除违规的行像这样:
Ideally, I would just remove the offending row from the CSV like so:
...
if row[@headersHash['foo']] == 'false'
@csv.delete(true) #Doesn't work
...
查看ruby文档,看起来像 row
类有一个 delete_if
函数。我对该函数需要的语法感到困惑。有没有办法删除该行而不创建新的csv对象?
Looking at the ruby documentation, it looks like the row
class has a delete_if
function. I'm confused on the syntax that that function requires. Is there a way to remove the row without making a new csv object?
http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Row .html#method-i-each
推荐答案
您应该可以使用CSV::Table#delete_if
,但您需要使用 CSV: :table
而不是 CSV :: read
,因为前者会为您提供一个CSV :: Table对象,而后者结果在数组数组。请注意,此设置也会将标题转换为符号。
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的CSV中删除一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!