[Numpy-tickets] [NumPy] #663: Support for multi formatting elements in savetxt
NumPy
numpy-tickets@scipy....
Thu Feb 21 15:38:31 CST 2008
#663: Support for multi formatting elements in savetxt
-------------------------+--------------------------------------------------
Reporter: dhuard | Owner: somebody
Type: enhancement | Status: new
Priority: normal | Milestone: 1.0.5
Component: Other | Version: none
Severity: normal | Keywords:
-------------------------+--------------------------------------------------
Here is a patch to add support for multiple formats in savetxt.
{{{
Index: numpy/lib/io.py
===================================================================
--- numpy/lib/io.py (revision 4815)
+++ numpy/lib/io.py (working copy)
@@ -326,6 +326,10 @@
the file is automatically saved in compressed gzip format. The
load()
command understands gzipped files transparently.
+ fmt can be a single format (%10.5f), a sequence of formats, or a
+ single multi-format string, e.g. 'Iteration %d -- %10.5f', in which
+ case delimiter is ignored.
+
Example usage:
save('test.out', X) # X is an array
@@ -354,8 +358,23 @@
if len(X.shape)==1:
origShape = X.shape
X.shape = len(X), 1
+
+ # Fmt can be a string with multiple insertion points or a list of
formats.
+ # E.g. '%10.5f\t%10d' or ('%10.5f', '$10d')
+ if type(fmt) in (list, tuple):
+ if len(fmt) != X.shape[1]:
+ raise AttributeError, 'fmt has wrong shape. '+ str(fmt)
+ format = delimiter.join(fmt)
+ elif type(fmt) is str:
+ if fmt.count('%') == 1:
+ fmt = [fmt,]*X.shape[1]
+ format = delimiter.join(fmt)
+ elif fmt.count('%') != X.shape[1]:
+ raise AttributeError, 'fmt has wrong number of % formats. '
+ fmt
+ else:
+ format = fmt
for row in X:
- fh.write(delimiter.join([fmt%val for val in row]) + '\n')
+ fh.write(format%tuple(row) + '\n')
if origShape is not None:
X.shape = origShape
}}}
--
Ticket URL: <http://scipy.org/scipy/numpy/ticket/663>
NumPy <http://projects.scipy.org/scipy/numpy>
The fundamental package needed for scientific computing with Python.
More information about the Numpy-tickets
mailing list