How to read lines of a file in Ruby

浪子不回头ぞ 提交于 2019-11-26 10:07:04

问题


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.


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?


回答1:


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.

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.




回答2:


Ruby does have a method for this:

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

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




回答3:


File.foreach(filename).with_index do |line, line_num|
   puts "#{line_num}: #{line}"
end

This will execute the given block for each line in the file without slurping the entire file into memory. See: IO::foreach.




回答4:


Your first file has Mac Classic line endings (that’s "\r" instead of the usual "\n"). Open it with

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

to specify the line endings.




回答5:


It is because of the endlines in each lines. Use the chomp method in ruby to delete the endline '\n' or 'r' at the end.

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



回答6:


I'm partial to the following approach for files that have headers:

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

This allows you to process a header line (or lines) differently than the content lines.




回答7:


how about gets ?

myFile=File.open("paths_to_file","r")
while(line=myFile.gets)
 //do stuff with line
end



回答8:


Don't forget that if you are concerned about reading in a file that might have huge lines that could swamp your RAM during runtime, you can always read the file piece-meal. See "Why slurping a file is bad".

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


来源:https://stackoverflow.com/questions/6012930/how-to-read-lines-of-a-file-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!