0

我一直面临文件概念的一些问题。我有一个文本文件,其中有 1000 行。我想将该文件分成 2 个,每个应该包含 500 行。为此,我编写了以下代码,但它通过提供一定的内存空间来拆分它。

class Hello
  def chunker f_in, out_pref, chunksize = 500
  File.open(f_in,"r") do |fh_in|
    until fh_in.eof?
      ch_path = "/my_applications//#{out_pref}_#{"%05d"%(fh_in.pos/chunksize)}.txt"
      puts "choose path: "
      puts ch_path
      File.open(ch_path,"w") do |fh_out|
        fh_out << fh_in.read(chunksize)
        puts "FH out : "
        puts fh_out  
      end
    end
   end
  end
end

f=Hello.new
f.chunker "/my_applications/hello.txt", "output_prefix"


我可以根据内存大小(500kb)拆分父文件。但我希望它按行数分开。我怎样才能做到这一点。
请帮我。

4

2 回答 2

4

计算中间线pivot,并据此输出。

out1 = File.open('output_prefix1', 'w')
out2 = File.open('output_prefix2', 'w')
File.open('/my_applications/hello.txt') do |file|
  pivot = file.lines.count / 2
  file.rewind
  file.lines.each_with_index do |line, index|
    if index < pivot
      out1.write(line)
    else
      out2.write(line)
    end
  end
end
out1.close
out2.close
于 2013-03-25T14:14:55.313 回答
2

file = File.readlines('hello.txt')

File.open('first_half.txt', 'w') {|new_file| new_file.puts file[0...500]} File.open('second_half.txt', 'w') {|new_file| new_file.puts file[500...1000]}

于 2013-03-25T14:06:33.213 回答