Added write_csv function to export a dataset to regular comma/tab/whatever separated files.

This commit is contained in:
Einar Ryeng 2009-02-09 23:05:09 +00:00
parent 0858fd00e5
commit 53cbd8fed7

View File

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