From 53cbd8fed7ae755f5a23b66144f744c59c4b33b2 Mon Sep 17 00:00:00 2001 From: einarr Date: Mon, 9 Feb 2009 23:05:09 +0000 Subject: [PATCH] Added write_csv function to export a dataset to regular comma/tab/whatever separated files. --- laydi/dataset.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/laydi/dataset.py b/laydi/dataset.py index 54cf9a8..1ab7f1b 100644 --- a/laydi/dataset.py +++ b/laydi/dataset.py @@ -707,6 +707,50 @@ def read_ftsv(fd, sep=None): return ds +def write_csv(fd, ds, decimals=7, sep='\t'): + """Write a dataset as comma/tab/whatever dilimited data. + + @param fd: An open file descriptor to the output file. + @param ds: The dataset to be written. + @param decimals: Number of decimals, only supported for dataset. + @param sep: Value separator + """ + + ## Open file if a string is passed instead of a file descriptor + opened = False + if isinstance(fd, str): + fd = open(fd, 'w') + opened = True + + ## Get data + rowdim, coldim = ds.get_dim_name() + rowids = ds.get_identifiers(rowdim) + colids = ds.get_identifiers(coldim) + a = ds.asarray() + y, x = a.shape + fmt = '%%%if' % decimals + + ## Write header + fd.write(rowdim) + fd.write(sep) + for i, id in enumerate(colids): + fd.write(id) + fd.write(sep) + fd.write('\n') + + ## Write matrix data + for j in range(y): + fd.write(rowids[j]) + fd.write(sep) + for i in range(x): + fd.write(fmt % (a[j, i],)) + fd.write(sep) + fd.write('\n') + + ## If we opened the stream, close it + if opened: + fd.close() + def _write_sparse_elements(fd, arr, fmt='%d', sep=None): """ Sparse coordinate format.""" fd.write('# sp_format: True\n\n')