【问题标题】:Take x number of rows from CSV file and remove them from the CSV in the process从 CSV 文件中获取 x 行并在此过程中从 CSV 中删除它们
【发布时间】:2021-04-06 09:43:24
【问题描述】:

我需要解析用户输入的 CSV 文件并上传所述 CSV 文件的片段。我想从表中取出前 5 行并在此过程中将它们删除。

我正在查看 Ruby CSV 文档,但似乎找不到任何可以满足我需求的内容。

我正在寻找类似 @​​987654321@ delete 的方法,但适用于 CSV。 Ruby 是否存在这种情况?

CSV.foreach(csv_path, headers: false).take(5)

这几乎是我想要的,但我还需要在此过程中从表中删除这些行。

【问题讨论】:

  • 有点不清楚你所说的“并在过程中删除它们”是什么意思,你的意思是实际上从文件中删除这些行吗?
  • 是的。我想首先获取这些行并对它们进行一些处理,然后将它们从文件/表中永久删除,这样我就可以重复这个过程,直到表中没有行。
  • 那么您真正想做的是以 5 个为单位处理文件吗?
  • 你能解释一下这个过程背后的原因吗,因为这是我目前无法理解的 IO 密集型。就像@max 说的那样,您是否只想读取 5 个块,因为这不需要打开/读取/更改/保存周期
  • 因此您不需要从原始文件中删除它们,您需要以块的形式创建新的 CSV 文件。正确的?如果这是真的,那么@max 已经提供了答案。只是CSV.foreach(...).each_slice(x) 将创建一个枚举器,它为给定块产生“x”行。然后你只需要将这些块写入一个新的 CSV

标签: ruby csv


【解决方案1】:

创建一个 CSV 文件用于说明。

File.write('t.csv', <<~END
Now,is,the
time,for,all
good,Rubiests,to
come,to,the
aid,of,their
bowling,team,.
END
)

让我们看看吧。

puts File.read('t.csv')
Now,is,the
time,for,all
good,Rubiests,to
come,to,the
aid,of,their
bowling,team,.

如果要跳过索引在rng范围内的行,

require 'csv'
rng = 1..3
CSV.foreach('t.csv').reject.with_index { |_,i| rng.cover?(i) }
  #=> [["Now", "is", "the"],
  #    ["aid", "of", "their"],
  #    ["bowling", "team", "."]]

如果需要,请使用 select 而不是 reject

更一般地,如果要跳过其索引在数组arr 中的行,

arr = [1, 3, 4]
CSV.foreach('t.csv').reject.with_index { |_,i| arr.include?(i) }
  #=> [["Now", "is", "the"],
  #    ["good", "Rubiests", "to"],
  #    ["bowling", "team", "."]]

也可以这样写。

arr = [1, 3, 4]
x, y = CSV.foreach('t.csv').partition.with_index { |_,i| arr.include?(i) }
x #=> [["time", "for", "all"], ["come", "to", "the"], ["aid", "of", "their"]] 
y #=> [["Now", "is", "the"], ["good", "Rubiests", "to"], ["bowling", "team", "."]] 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-03
    • 1970-01-01
    • 2016-04-10
    • 2020-07-18
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多