265

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

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

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


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

4

8 回答 8

576

Ruby 确实有一个方法:

File.readlines('foo').each do |line|
    puts(line)
end

http://ruby-doc.org/core-1.9.3/IO.html#method-c-readlines

于 2012-08-15T18:31:35.377 回答
426
File.foreach(filename).with_index do |line, line_num|
   puts "#{line_num}: #{line}"
end

这将为文件中的每一行执行给定的块,而不会将整个文件放入内存中。请参阅:IO::foreach

于 2013-07-02T00:31:57.863 回答
153

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

为了支持"\r"EOL 字符以及常规的"\n", 和"\r\n"Windows,这就是我要做的:

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

当然,这对于非常大的文件可能不是一个好主意,因为这意味着将整个文件加载到内存中。

于 2011-05-16T03:50:41.890 回答
19

您的第一个文件具有 Mac Classic 行尾("\r"而不是通常的"\n")。打开它

File.open('foo').each(sep="\r") do |line|

指定行尾。

于 2011-05-16T03:36:18.513 回答
8

对于具有标题的文件,我偏爱以下方法:

File.open(file, "r") do |fh|
    header = fh.readline
    # Process the header
    while(line = fh.gets) != nil
        #do stuff
    end
end

这允许您以不同于内容行的方式处理标题行(或行)。

于 2014-05-29T20:41:29.487 回答
7

这是因为每一行都有结束线。使用 ruby​​ 中的 chomp 方法删除末尾的结束行 '\n' 或 'r'。

line_num=0
File.open('xxx.txt').each do |line|
  print "#{line_num += 1} #{line.chomp}"
end
于 2014-06-30T05:45:20.283 回答
7

得到怎么样?

myFile=File.open("paths_to_file","r")
while(line=myFile.gets)
 //do stuff with line
end
于 2014-08-19T19:47:18.223 回答
4

不要忘记,如果您担心读取的文件可能包含可能在运行时占用您的 RAM 的大行,您可以随时读取文件。请参阅“为什么 slurping 文件不好”。

File.open('file_path', 'rb') do |io|
  while chunk = io.read(16 * 1024) do
    something_with_the chunk
    # like stream it across a network
    # or write it to another file:
    # other_io.write chunk
  end
end
于 2014-12-10T07:20:07.933 回答