VenkatK
VenkatK

Reputation: 1305

How to split a text file into 2 files using number of lines?

I have been facing some issue with file concepts. I have a text file in which I have 1000 lines. I want to split that file into 2 and each of which should contain 500 lines. For that I wrote the following code, but it splits that by giving certain memory space.

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"


I am able to split the parent file according to memory size(500kb). But I want that gets splitted by number of lines. How can I achieve that.
Please help me.

Upvotes: 0

Views: 1174

Answers (2)

toch
toch

Reputation: 3945

Calculating the middle line pivot, and output according it.

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

Upvotes: 4

slowpoke
slowpoke

Reputation: 143

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]}

Upvotes: 2

Related Questions