如何删除csv的第一行? (红宝石)

发布于 2024-09-14 01:47:56 字数 89 浏览 3 评论 0原文

我有一个很大的 csv。我想删除文件的第一行。这是怎么做到的?我不想将每一行复制到数组中并为前一个索引重写它们并删除第一个。一定有更好的方法。

谢谢

I have a large csv. I want to delete the first line of the file. How is this done? I don't want to copy every line into an array and rewrite them for the previous index and delete the first. There must be a better way.

thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不爱素颜 2024-09-21 01:47:56

虽然 Guffa 关于在标题中可以有换行符的说法是正确的,但这并不常见,所以如果您可以忽略这种边缘情况,您可以使用:

File.open('new.csv', 'w+') do |outf|
  File.open('original.csv') do |inf|
    inf.each_line.with_index do |line, i|
      outf.write line unless i==0
    end
  end
end

如果这对您来说太慢,请告诉我,我们将重写它使用块读取而不是实际解析整个文件。

Although Guffa is right about having linebreaks in header is possible, that's not that usual, so if you're ok with ignoring that edge case, you can use:

File.open('new.csv', 'w+') do |outf|
  File.open('original.csv') do |inf|
    inf.each_line.with_index do |line, i|
      outf.write line unless i==0
    end
  end
end

If this is too slow for you, let me know and we'll rewrite this to use block reading instead actually parsing the whole file.

勿挽旧人 2024-09-21 01:47:56

好吧,您可以采取一些快捷方式,但有几件事您无法规避:

  • 根据编码的不同,字符可能不会映射到文件中的单个字节,因此您必须读取它作为文本。

  • 您必须至少解析文件的第一条记录。 CSV 格式不是基于行的,尽管它使用换行符来分隔记录。值还可以包含换行符,因此您不能只读取到第一个换行符并理所当然地认为这是第一条记录。

  • 没有办法删除文件的一部分,所以无论你做什么,你仍然必须重写整个文件。

    没有

因此,您可以解析标头(如果有)和第一条记录,然后您可以以纯文本形式读取文件的其余部分。然后,您可以将其余部分写回第一条记录开始的位置(或从文件开头写入并包含标题)。

Well, there are some shortcuts that you can take, but there are several things that you can't circumvent:

  • Depending on the encoding, a character might not map to a single byte in the file, so you have to read it as text.

  • You have to parse at least the first record of the file. The CSV format is not line based eventhough it uses line breaks to separate records. A value can also contain a line break, so you can't just read to the first line break and take for granted that this is the first record.

  • There is no way to delete part of a file, so whatever you do you still have to rewrite the entire file.

So, you can parse the header (if there is one) and the first record, then you can read the rest of the file as plain text. Then you can write the rest back at the position where the first record started (or write from the start of the file and include the header).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文