简体   繁体   English

如何使用行数将文本文件分为2个文件?

[英]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. 我有一个文本文件,其中有1000行。 I want to split that file into 2 and each of which should contain 500 lines. 我想将该文件分成2个,每个文件应包含500行。 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). 我可以根据内存大小(500kb)分割父文件。 But I want that gets splitted by number of lines. 但是我希望按行数划分。 How can I achieve that. 我该如何实现。
Please help me. 请帮我。

Calculating the middle line pivot , and output according it. 计算中线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

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

File.open('first_half.txt', 'w') {|new_file| new_file.puts file[0...500]} 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]} 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]} File.open('second_half.txt', 'w') {|new_file| new_file.puts file[500...1000]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM