如何在 Ruby 中读取文件的行

发布于 2024-11-07 10:12:26 字数 462 浏览 6 评论 0原文

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

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

但是这个文件 分别打印每一行。


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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

勿忘初心 2024-11-14 10:12:26

Ruby 确实有一个方法:

File.readlines('foo', chomp: true).each do |line|
    puts(line)
end

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

Ruby does have a method for this:

File.readlines('foo', chomp: true).each do |line|
    puts(line)
end

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

迷离° 2024-11-14 10:12:26
File.foreach(filename).with_index do |line, line_num|
   puts "#{line_num}: #{line}"
end

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

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.

败给现实 2024-11-14 10:12:26

我相信我的答案涵盖了您对处理任何类型的行结尾的新担忧,因为 "\r\n""\r" 都转换为 Linux 标准 在解析行之前使用“\n”

要支持 "\r" EOL 字符以及 Windows 中的常规 "\n""\r\n",如下我会做什么:

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

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

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.

一袭水袖舞倾城 2024-11-14 10:12:26

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

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

指定行结尾。

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.

゛时过境迁 2024-11-14 10:12:26

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

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

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

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.

绿萝 2024-11-14 10:12:26

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

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

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
听不够的曲调 2024-11-14 10:12:26

gets 怎么样?

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

how about gets ?

myFile=File.open("paths_to_file","r")
while(line=myFile.gets)
 //do stuff with line
end
骷髅 2024-11-14 10:12:26

不要忘记,如果您担心读取的文件中可能包含大量行,从而在运行时会淹没您的 RAM,那么您始终可以分段读取该文件。请参阅“为什么读取文件不好”。

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

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
薄暮涼年 2024-11-14 10:12:26

已经有无数的答案,但这里是为那些喜欢使用路径名的人提供的一个。

Pathname('ruby.rb').each_line(chomp: true).to_a

There's already a bazillion answers, but here is one for those who like to use Pathnames.

Pathname('ruby.rb').each_line(chomp: true).to_a
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文