Writes fasta file to be used with -f option of prepareref
345429
def write_prepareref_fasta_file(outfile, gene_coords, genes_need_upstream, genes_non_upstream, upstream_before=100, upstream_after=100):
    ''''''
    tmp_dict = {}
    fasta_in = os.path.join(data_dir, 'NC_000962.3.fa.gz')
    pyfastaq.tasks.file_to_dict(fasta_in, tmp_dict)
    ref_seq = tmp_dict['NC_000962.3']

    with open(outfile, 'w') as f:
        for gene in genes_non_upstream:
            start = gene_coords[gene]['start']
            end = gene_coords[gene]['end']
            if start < end:
                gene_fa = pyfastaq.sequences.Fasta(gene, ref_seq[start:end+1])
            else:
                gene_fa = pyfastaq.sequences.Fasta(gene, ref_seq[end:start+1])
                gene_fa.revcomp()

            print(gene_fa, file=f)

        for gene in genes_need_upstream:
            start = gene_coords[gene]['start']
            end = gene_coords[gene]['end']
            if start < end:
                gene_fa = pyfastaq.sequences.Fasta(gene, ref_seq[start - upstream_before:start + upstream_after])
            else:
                gene_fa = pyfastaq.sequences.Fasta(gene, ref_seq[start - upstream_after + 1:start + upstream_before + 1])
                gene_fa.revcomp()

            gene_fa.id += '_upstream'
            print(gene_fa, file=f)
1082530
def write(self):
        

        rabs = [x.seqrecord for x in self.gproteins.values() if x.is_rab()]
        return SeqIO.write(rabs, self.tmpfname + '.phase2', 'fasta')
482044
def _write_int(fname, data, append=True):
    """"""
    # pylint: disable=W0705
    data_ex = pexdoc.exh.addex(ValueError, "There is no data to save to file")
    fos_ex = pexdoc.exh.addex(
        OSError, "File *[fname]* could not be created: *[reason]*"
    )
    data_ex((len(data) == 0) or ((len(data) == 1) and (len(data[0]) == 0)))
    try:
        pmisc.make_dir(fname)
        mode = "w" if append is False else "a"
        if sys.hexversion < 0x03000000:  # pragma: no cover, no branch
            with open(fname, mode) as file_handle:
                csv.writer(file_handle, delimiter=",").writerows(data)
        else:  # pragma: no cover
            with open(fname, mode, newline="") as file_handle:
                csv.writer(file_handle, delimiter=",").writerows(data)
    except (IOError, OSError) as eobj:
        fos_ex(True, _MF("fname", fname, "reason", eobj.strerror))
1093845
def write_to(self, f, version = None):
        
        if not version:
            version = self.version
        if version == 1:
            header = "%(url)s %(ip_address)s %(date)s %(content_type)s %(length)s"
        elif version == 2:
            header = "%(url)s %(ip_address)s %(date)s %(content_type)s %(result_code)s %(checksum)s %(location)s %(offset)s %(filename)s %(length)s"

        header =  header%dict(url          = self['url'],
                              ip_address   = self['ip_address'],
                              date         = self['date'],
                              content_type = self['content_type'],
                              result_code  = self['result_code'],
                              checksum     = self['checksum'],
                              location     = self['location'],
                              offset       = self['offset'],
                              filename     = self['filename'],
                              length       = self['length'])
        f.write(header)
819050
def fh_to_record(self, f):
        """"""

        fn_path = self.file_name
        fr = self.record
        fr.path = fn_path

        fr.update_contents(f.read(), 'text/plain')

        fr.source_hash = self.fs_hash
        fr.synced_fs = self.fs_modtime
        fr.modified = self.fs_modtime
1216556
def record_to_fs(self):
        """"""

        fr = self.record

        if fr.contents:
            with self._fs.open(self.file_name, 'w', encoding='utf-8') as f:
                self.record_to_fh(f)
1044928
def write_worker(q_out, fname, working_dir):
    
    pre_time = time.time()
    count = 0
    fname = os.path.basename(fname)
    fname_rec = os.path.splitext(fname)[0] + '.rec'
    fname_idx = os.path.splitext(fname)[0] + '.idx'
    record = mx.recordio.MXIndexedRecordIO(os.path.join(working_dir, fname_idx),
                                           os.path.join(working_dir, fname_rec), 'w')
    buf = {}
    more = True
    while more:
        deq = q_out.get()
        if deq is not None:
            i, s, item = deq
            buf[i] = (s, item)
        else:
            more = False
        while count in buf:
            s, item = buf[count]
            del buf[count]
            if s is not None:
                record.write_idx(item[0], s)

            if count % 1000 == 0:
                cur_time = time.time()
                print('time:', cur_time - pre_time, ' count:', count)
                pre_time = cur_time
            count += 1
211318
def fastaAlignmentRead(fasta, mapFn=(lambda x : x), l=None):
    
    if l is None:
        l = _getMultiFastaOffsets(fasta)
    else:
        l = l[:]
    seqNo = len(l)
    for i in xrange(0, seqNo):
        j = open(fasta, 'r')
        j.seek(l[i])
        l[i] = j
    column = [sys.maxint]*seqNo
    if seqNo != 0:
        while True:
            for j in xrange(0, seqNo):
                i = l[j].read(1)
                while i == '\n':
                    i = l[j].read(1)
                column[j] = i
            if column[0] == '>' or column[0] == '':
                for j in xrange(1, seqNo):
                    assert column[j] == '>' or column[j] == ''
                break
            for j in xrange(1, seqNo):
                 assert column[j] != '>' and column[j] != ''
                 column[j] = mapFn(column[j])
            yield column[:]
    for i in l:
        i.close()
408073
def write(self, fn=None):
        """"""
        fn = fn or self.fn
        if not os.path.exists(os.path.dirname(fn)):
            os.makedirs(os.path.dirname(fn))
        f = open(self.fn, 'rb')
        b = f.read()
        f.close()
        f = open(fn, 'wb')
        f.write(b)
        f.close()
562087
def saveParList(self, *args, **kw):
        """"""
        if 'filename' in kw:
            filename = kw['filename']
        if not filename:
            filename = self.getFilename()
        if not filename:
            raise ValueError("No filename specified to save parameters")

        if hasattr(filename,'write'):
            fh = filename
            absFileName = os.path.abspath(fh.name)
        else:
            absFileName = os.path.expanduser(filename)
            absDir = os.path.dirname(absFileName)
            if len(absDir) and not os.path.isdir(absDir): os.makedirs(absDir)
            fh = open(absFileName,'w')
        numpars = len(self.__paramList)
        if self._forUseWithEpar: numpars -= 1
        if not self.final_comment: self.final_comment = [''] # force \n at EOF
        # Empty the ConfigObj version of section.defaults since that is based
        # on an assumption incorrect for us, and override with our own list.
        # THIS IS A BIT OF MONKEY-PATCHING!  WATCH FUTURE VERSION CHANGES!
        # See Trac ticket #762.
        while len(self.defaults):
            self.defaults.pop(-1) # empty it, keeping ref
        for key in self._neverWrite:
            self.defaults.append(key)
        # Note also that we are only overwriting the top/main section's
        # "defaults" list, but EVERY [sub-]section has such an attribute...

        # Now write to file, delegating work to ConfigObj (note that ConfigObj
        # write() skips any items listed by name in the self.defaults list)
        self.write(fh)
        fh.close()
        retval = str(numpars) + " parameters written to " + absFileName
        self.filename = absFileName # reset our own ConfigObj filename attr
        self.debug('Keys not written: '+str(self.defaults))
        return retval
330756
def writeData(f, data):
    
    if not isinstance(data, dict):
      raise Exception(PyVDF.__ERR_NotDict.format(repr(data)))
    data = PyVDF.formatData(data)
    try:
      f.write(data)
    except AttributeError:
      pass

    try:
      filec = open(f, 'w')
      filec.write(data)
      filec.close()
    except IOError as e:
      print("Could not open '" + f + "' for writing.")
      print(e)
866167
def write(self, arg, **kwargs):
        """"""
        if hasattr(arg, 'seek'):
            self._tofile(arg, **kwargs)
        else:
            with open(arg, 'wb') as fid:
                self._tofile(fid, **kwargs)
352361
def splitFASTA(params):
    
    assert params['fastaFile'][-1] == 'a', ('You must specify a file in '
                                            'fasta-format that ends in '
                                            '.fasta')

    fileCount = count = seqCount = 0
    outfp = None
    with open(params['fastaFile']) as infp:
        for seq in SeqIO.parse(infp, 'fasta'):
            seqCount += 1
            if count == params['seqsPerJob']:
                outfp.close()
                count = 0
            if count == 0:
                outfp = open('%d.fasta' % fileCount, 'w')
                fileCount += 1
            count += 1
            outfp.write('>%s\n%s\n' % (seq.description, str(seq.seq)))
    outfp.close()
    return fileCount, seqCount
1068509
def fastqIterate(infile):
    ''''''

    def convert2string(b):
        if type(b) == str:
            return b
        else:
            return b.decode("utf-8")

    while 1:
        line1 = convert2string(infile.readline())
        if not line1:
            break
        if not line1.startswith('@'):
            U.error("parsing error: expected '@' in line %s" % line1)
        line2 = convert2string(infile.readline())
        line3 = convert2string(infile.readline())
        if not line3.startswith('+'):
            U.error("parsing error: expected '+' in line %s" % line3)
        line4 = convert2string(infile.readline())
        # incomplete entry
        if not line4:
            U.error("incomplete entry for %s" % line1)

        yield Record(line1[1:-1], line2[:-1], line4[:-1])
265983
def atomic_write(path, mode):
  """"""
  tmp_path = "%s%s_%s" % (path, constants.INCOMPLETE_SUFFIX, uuid.uuid4().hex)
  with tf.io.gfile.GFile(tmp_path, mode) as file_:
    yield file_
  tf.io.gfile.rename(tmp_path, path, overwrite=True)
78755
def write(self, filepath, skip_unknown=False):
        """"""
        fp = codecs.open(filepath, 'w', encoding='utf-8')
        try:
            self.write_file(fp, skip_unknown)
        finally:
            fp.close()
1199766
def merge(args):
    
    p = OptionParser(merge.__doc__)
    p.add_option("--seq", default=False, action="store_true",
                 help="Print FASTA sequences at the end")
    p.set_outfile()

    opts, args = p.parse_args(args)

    nargs = len(args)
    if nargs < 1:
        sys.exit(not p.print_help())

    if nargs == 1:
        listfile, = args
        fp = open(listfile)
        gffiles = [x.strip() for x in fp]
    else:
        gffiles = args

    outfile = opts.outfile

    deflines = set()
    fw = must_open(outfile, "w")
    fastarecs = {}
    for gffile in natsorted(gffiles, key=lambda x: op.basename(x)):
        logging.debug(gffile)
        fp = open(gffile)
        for row in fp:
            row = row.rstrip()
            if not row or row[0] == '#':
                if row == FastaTag:
                    break
                if row in deflines:
                    continue
                else:
                    deflines.add(row)

            print(row, file=fw)

        if not opts.seq:
            continue

        f = Fasta(gffile, lazy=True)
        for key, rec in f.iteritems_ordered():
            if key in fastarecs:
                continue
            fastarecs[key] = rec

    if opts.seq:
        print(FastaTag, file=fw)
        SeqIO.write(fastarecs.values(), fw, "fasta")

    fw.close()