forked from mhm-ufz/mHM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfwrite.py
executable file
·93 lines (71 loc) · 3.01 KB
/
fwrite.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/env python
from __future__ import print_function
import numpy as np
def fwrite(fname, arr, header=None, precision='10.0'):
"""
Write numbers of 2D-array to a file.
A header can be given as optional as well as a precision.
Definition
----------
def fwrite(fname, data, header=None, precision='10.0'):
Input
-----
fname target file name
arr 2d numpy array to write
Optional Input Parameters
-------------------------
header list of header elements: a header element is a list of two strings:
the first entry is the header argument, the second the value
precision floating point precision of array to write
Examples
--------
>>> from ufz import fread
>>> # Clean up doctest
>>> filename = 'fwrite.test'
>>> header = [['Description', 'testing'], ['author', 'ST']]
>>> data = np.arange(10).reshape(2, 5)
>>> fwrite(filename, data, header=header)
>>> fread(filename, nc=2, skip=2, header=True)
[['Description', 'testing'], ['author', 'ST']]
>>> fread(filename, skip=2)
array([[ 0., 1., 2., 3., 4.],
[ 5., 6., 7., 8., 9.]])
>>> import os
>>> os.remove(filename)
License
-------
This file is part of the UFZ Python package.
The UFZ Python package is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The UFZ Python package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the UFZ makefile project (cf. gpl.txt and lgpl.txt).
If not, see <http://www.gnu.org/licenses/>.
Copyright 2009-2015 Stephan Thober
History
-------
Written, ST, Feb 2016
Modified,
"""
if not type(arr) is np.ndarray:
raise ValueError('function fwrite: argument arr must be numpy.ndarray')
fo = open(fname, 'w')
if not header is None:
# write header
for ll in np.arange(len(header)):
write_str = str(header[ll][0]) + ' ' + str(header[ll][1]) + '\n'
fo.write(write_str)
# write arr
for ll in np.arange(arr.shape[0]):
# format is mRM compatible
write_str = ' '.join(['{:' + precision + 'f}'] * arr.shape[1]).format(*arr[ll, :]) + '\n'
fo.write(write_str)
fo.close()
if __name__ == '__main__':
import doctest
doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)