如何从文件中获取特定的行 [英] How to get a particular line from a file

查看:133
本文介绍了如何从文件中获取特定的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能从文件中提取一个知道行号的特定行?例如,只需从文件text.txt中获取行 N 的内容?

解决方案请尝试以下两种解决方案之一:

$ p $ file = File.openfile.txt

#1解决方案会吃很多RAM
p [* file] [n-1]

#2解决方案不会
n次{file.gets}
p $ _

file.close


Is it possible to extract a particular line from a file knowing its line number? For example, just get the contents of line N as a string from file "text.txt"?

解决方案

Try one of these two solutions:

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

这篇关于如何从文件中获取特定的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆