在 Ruby 中读取选择性文件
我有一个巨大的文件,如下所示:
7
bla1
blala
blabla
blab
blals
blable
bla
more here..
第一个数字告诉我将有多少个值。问题是,我只想直接指向第 11 行(文本“更多此处..”),而不必之前读取所有这些值。就我而言,我有大量数字,因此必须对其进行优化。
你能给我推荐一些东西吗?
I have a huge file that looks like this:
7
bla1
blala
blabla
blab
blals
blable
bla
more here..
The first numbers tells how many values I will have. The thing, is that i just want to point directly to the line 11 (text "more here.."), without having to read all those values before. In my case, I have a big amount of numbers, so it has to be optimized.
Would you recommend me something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 File#seek 随机访问该文件。
这种方法的问题在于,它只会访问指定字节偏移量的数据,而不是行偏移量。如果您的文件可以给出文件开头到列表结束位置的字节偏移量,那么您可以使用它。
You could probably use File#seek to randomly access the file.
The problem with that approach is that it will just access data at a specified byte offset - not a line offset. If your file could give the byte offset at the start of the file to where the list finishes, then you could use that.
您可以制作类似文件的内容,跳过前 N 行:
就像这样:
如果您只想向前迭代文件的行,那么很容易做到。然而,如果您想精确地模仿
File
或IO
接口(但请参阅Delegate
),特别是如果您想支持回滚到文件的假开头。You can make something file-like that will skip past the first N lines:
Like so:
Easy to do if you just want to iterate forward through lines of a file. It becomes arduous, however, if you want to mimic the
File
orIO
interface exactly (but seeDelegate
) and especially if you want to support rewindability back to the fake start of your file.这是一种优雅的方法,但可能不是很有效,因为它需要立即将整个文件加载到内存中。
Here's an elegant way to do it, probably not very efficient though as it requires loading the whole file into memory at once.
我认为您不会比这更有效,因为您将读取文件中的字节来找出什么是“行”。
I don't think you're going to get any more efficient than this, since you'll have read the bytes in the file to figure out what is a "line".