如何在Ruby中读取文件的行 [英] How to read lines of a file in Ruby

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

问题描述

我试图使用以下代码从文件中读取行.但是在读取文件时,内容都在一行:

I was trying to use the following code to read lines from a file. But when reading a file, the contents are all in one line:

line_num=0
File.open('xxx.txt').each do |line|
  print "#{line_num += 1} #{line}"
end

但是这个文件单独打印每一行.

But this file prints each line separately.

我必须使用标准输入,比如 ruby my_prog.rb <file.txt,我无法假设文件使用的行尾字符是什么.我该如何处理?

I have to use stdin, like ruby my_prog.rb < file.txt, where I can't assume what the line-ending character is that the file uses. How can I handle it?

推荐答案

我相信我的回答涵盖了您对处理任何类型的行尾的新担忧,因为 "\r\n">"\r" 在解析行之前转换为 Linux 标准 "\n".

I believe my answer covers your new concerns about handling any type of line endings since both "\r\n" and "\r" are converted to Linux standard "\n" before parsing the lines.

支持 "\r" EOL 字符以及常规 "\n""\r\n" 来自Windows,这是我会做的:

To support the "\r" EOL character along with the regular "\n", and "\r\n" from Windows, here's what I would do:

line_num=0
text=File.open('xxx.txt').read
text.gsub!(/\r\n?/, "\n")
text.each_line do |line|
  print "#{line_num += 1} #{line}"
end

当然,这对于非常大的文件来说可能是个坏主意,因为这意味着将整个文件加载到内存中.

Of course this could be a bad idea on very large files since it means loading the whole file into memory.

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

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