Jon*_*röm 22
你可以通过索引得到它readlines.
line = IO.readlines("file.txt")[42]
Run Code Online (Sandbox Code Playgroud)
如果它是一个小文件,请仅使用它.
Nak*_*lon 14
尝试以下两种解决方案之一:
file = File.open "file.txt"
#1 solution would eat a lot of RAM
p [*file][n-1]
#2 solution would not
n.times{ file.gets }
p $_
file.close
Run Code Online (Sandbox Code Playgroud)
def get_line_from_file(path, line)
result = nil
File.open(path, "r") do |f|
while line > 0
line -= 1
result = f.gets
end
end
return result
end
get_line_from_file("/tmp/foo.txt", 20)
Run Code Online (Sandbox Code Playgroud)
这是一个很好的解决方案,因为:
File.read,因此不会将整个文件读入内存。如果文件的大小为20MB,并且您经常阅读,因此GC不能跟上,这样做可能会成为问题。如果您想引发错误(),而不是在越界行时不返回nil gets,readline则可以替换为EOFError。