def convert(cls, filepath, other_file, buffersize=None, library=None): """Instantiate a BaseFile object from another BaseFile object. """ if not isinstance(other_file, BaseFile): raise CancerApiException("Must pass cancer_api file object as `other_file`.") obj = cls._init(filepath=filepath, parser_cls=None, other_file=other_file, is_new=True, buffersize=buffersize, library=library) obj.write() return obj
def add_obj(self, obj): """Add object to storelist. Useful to bind objects to files created with the `new` constructor. Returns whether the object was added (always True for now). """ if not isinstance(obj, CancerApiObject): raise CancerApiException("`add_obj` only supports cancer_api objects") self.storelist.append(obj) if self.buffersize and len(self.storelist) >= self.buffersize: self.write() return True
def write(self, outfilepath=None, mode="w"): """Write objects in file to disk. Either you can write to a new file (if outfilepath is given), or you can append what's in storelist to the current filepath. """ # If outfilepath is specified, iterate over every object in self # (which might come from something else) and every object in # self.storelist and write them out to disk if outfilepath: with open_file(outfilepath, mode) as outfile: logging.info("Writing to disk...") outfile.write(self.get_header()) for obj in self.source: line = self.obj_to_str(obj) outfile.write(line) for obj in self.storelist: line = self.obj_to_str(obj) outfile.write(line) # Clear storelist now that they've been written to disk self.clear_storelist() # Update file attributes (in case of new or converted file) self.source = self self.filepath = outfilepath self.is_new = False # If outfilepath is not specified, simply iterate over every # object in self.storelist and append them to the file on disk. else: # If the file is new and the path already exist, do not append if self.is_new and os.path.exists(self.filepath): raise CancerApiException( "Output file already exists: {}".format(self.filepath)) with open_file(self.filepath, "a+") as outfile: logging.info("Writing to disk...") # If the file is new, start with header if self.is_new: outfile.write(self.get_header()) # If file is new and source is not self (i.e., converted file), # iterate over source if self.is_new and self.source is not self: for obj in self.source: line = self.obj_to_str(obj) outfile.write(line) # Proceed with iterating over storelist for obj in self.storelist: line = self.obj_to_str(obj) outfile.write(line) # Clear storelist now that they've been written to disk self.clear_storelist() # Update file attributes (in case of new or converted file) self.source = self self.is_new = False
def __init__(self, *args, **kwargs): """Can't initialize directly.""" raise CancerApiException( "Please use `open`, `convert` or `new` methods instead.")