Projects/laydi
Projects
/
laydi
Archived
7
0
Fork 0

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
1 changed files with 44 additions and 0 deletions

View File

@ -707,6 +707,50 @@ def read_ftsv(fd, sep=None):
return ds 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): def _write_sparse_elements(fd, arr, fmt='%d', sep=None):
""" Sparse coordinate format.""" """ Sparse coordinate format."""
fd.write('# sp_format: True\n\n') fd.write('# sp_format: True\n\n')