-
-
Save vals/1f81b3cb9ce5fb91376b to your computer and use it in GitHub Desktop.
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
class FileSplitter(dict): | |
"""A class for efficientely writing to several file | |
""" | |
def __init__(self, output_base): | |
self.output_base = output_base | |
def __call__(self, num, line): | |
self.write_number(num, line) | |
def write_number(self, num, line): | |
fname = self.output_base.replace("--n--", "%04i" % num) | |
self.write_to_handles(num, line, fname) | |
def write_to_handles(self, num, line, fname): | |
try: | |
out_handle = self[fname] | |
except KeyError: | |
out_handle = open(fname, "a") | |
self[fname] = out_handle | |
out_handle.write("%s\n" % (line,)) | |
def close(self): | |
"""Close all the opened files. | |
""" | |
for handle in self.itervalues(): | |
handle.close() | |
out_format = "numbers_--n--.txt" | |
splitter = FileSplitter(out_format) | |
in_handle = open("numbers.txt") | |
for line in in_handle: | |
num = int(line) % 2000 | |
splitter(num, line) | |
in_handle.close() | |
splitter.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment