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')