def rec2csv(r, fname, delimiter='<STR_LIT:U+002C>', formatd=None, missing='<STR_LIT>',<EOL>missingd=None):
if missingd is None:<EOL><INDENT>missingd = dict()<EOL><DEDENT>def with_mask(func):<EOL><INDENT>def newfunc(val, mask, mval):<EOL><INDENT>if mask:<EOL><INDENT>return mval<EOL><DEDENT>else:<EOL><INDENT>return func(val)<EOL><DEDENT><DEDENT>return newfunc<EOL><DEDENT>formatd = get_formatd(r, formatd)<EOL>funcs = []<EOL>for i, name in enumerate(r.dtype.names):<EOL><INDENT>funcs.append(with_mask(csvformat_factory(formatd[name]).tostr))<EOL><DEDENT>fh, opened = cbook.to_filehandle(fname, '<STR_LIT:w>', return_opened=True)<EOL>writer = csv.writer(fh, delimiter=delimiter)<EOL>header = r.dtype.names<EOL>writer.writerow(header)<EOL>mvals = []<EOL>for name in header:<EOL><INDENT>mvals.append(missingd.get(name, missing))<EOL><DEDENT>ismasked = False<EOL>if len(r):<EOL><INDENT>row = r[<NUM_LIT:0>]<EOL>ismasked = hasattr(row, '<STR_LIT>')<EOL><DEDENT>for row in r:<EOL><INDENT>if ismasked:<EOL><INDENT>row, rowmask = row.item(), row._fieldmask.item()<EOL><DEDENT>else:<EOL><INDENT>rowmask = [False] * len(row)<EOL><DEDENT>writer.writerow([func(val, mask, mval) for func, val, mask, mval<EOL>in zip(funcs, row, rowmask, mvals)])<EOL><DEDENT>if opened:<EOL><INDENT>fh.close()<EOL><DEDENT>
Save the data from numpy recarray *r* into a
comma-/space-/tab-delimited file.  The record array dtype names
will be used for column headers.

*fname*: can be a filename or a file handle.  Support for gzipped
  files is automatic, if the filename ends in '.gz'

.. seealso::
    :func:`csv2rec`:
        For information about *missing* and *missingd*, which can
        be used to fill in masked values into your CSV file.