我试图使用以下代码从文件中读取行。但是当读取一个文件时,内容都在一行中:
line_num=0
File.open('xxx.txt').each do |line|
print "#{line_num += 1} #{line}"
end
但是这个文件单独打印每一行。
我必须使用标准输入,例如
ruby my_prog.rb < file.txt
,我无法假设文件使用的行结束字符是什么。我该如何处理?
Ruby 确实有一个方法:
File.readlines('foo', chomp: true).each do |line|
puts(line)
end
File.foreach(filename).with_index do |line, line_num|
puts "#{line_num}: #{line}"
end
这将为文件中的每一行执行给定的块,而不会将整个文件放入内存中。请参阅:IO::foreach。
我相信我的答案涵盖了您对处理任何类型的行结尾的新担忧,因为在解析行之前,
"\r\n"
和"\r"
都已转换为Linux标准"\n"
。
为了支持
"\r"
EOL 字符以及常规 "\n"
和 Windows 中的 "\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
当然,对于非常大的文件来说,这可能是一个坏主意,因为这意味着将整个文件加载到内存中。
您的第一个文件具有 Mac Classic 行结尾(即
"\r"
而不是通常的 "\n"
)。打开它
File.open('foo').each(sep="\r") do |line|
指定行结束符。
对于具有标题的文件,我偏向以下方法:
File.open(file, "r") do |fh|
header = fh.readline
# Process the header
while(line = fh.gets) != nil
#do stuff
end
end
这允许您以不同于内容行的方式处理标题行。
这是因为每行都有结束线。 使用ruby中的chomp方法删除尾行' ' 或 'r' 位于末尾。
line_num=0
File.open('xxx.txt').each do |line|
print "#{line_num += 1} #{line.chomp}"
end
得到怎么样?
myFile=File.open("paths_to_file","r")
while(line=myFile.gets)
//do stuff with line
end
不要忘记,如果您担心读取的文件中可能包含大量行,从而在运行时会淹没您的 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