如何删除csv的第一行? (红宝石)
我有一个很大的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然 Guffa 关于在标题中可以有换行符的说法是正确的,但这并不常见,所以如果您可以忽略这种边缘情况,您可以使用:
如果这对您来说太慢,请告诉我,我们将重写它使用块读取而不是实际解析整个文件。
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:
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.
好吧,您可以采取一些快捷方式,但有几件事您无法规避:
根据编码的不同,字符可能不会映射到文件中的单个字节,因此您必须读取它作为文本。
您必须至少解析文件的第一条记录。 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).