Created
March 23, 2014 03:16
-
-
Save unnitallman/9718112 to your computer and use it in GitHub Desktop.
CSV File splitter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Usage: FileSplitter.new('/usr/share/dict/words').split_into 10 | |
class FileSplitter | |
def initialize(path) | |
@file = File.open path | |
end | |
def split_into(n) | |
i = 1 | |
m = slice_size(n) | |
data_array.each_slice(m) do | batch | | |
data = batch.join("\n") | |
write_to_file(data, new_filename(i)) | |
i = i + 1 | |
end | |
end | |
private | |
def data_array | |
@data ||= @file.read.split("\n") | |
end | |
def new_filename(i) | |
"#{filename}_#{i}" | |
end | |
def filename | |
File.basename(@file.path) | |
end | |
def write_to_file(data, name) | |
open(name, 'w') do |f| | |
f.puts data | |
end | |
end | |
def slice_size(a) | |
(data_array.size/a) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment