Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/interfaces/read_data.py
4036 views
1
"""
2
An interface to read data files
3
"""
4
5
###############################################################################
6
# Sage: System for Algebra and Geometry Experimentation
7
# Copyright (C) 2010 Paul Zimmermann
8
# Distributed under the terms of the GNU General Public License (GPL),
9
# version 2 or later. The full text of the GPL is available at:
10
# http://www.gnu.org/licenses/
11
###############################################################################
12
13
def read_data(f,t):
14
r"""
15
Read data from file 'f' and class 't' (one element per line),
16
and returns a list of elements.
17
18
INPUT:
19
20
- 'f' - a file name
21
- 't' - a class (objects will be coerced to that class)
22
23
OUTPUT:
24
25
a list of elements of class 't'.
26
27
EXAMPLES::
28
29
sage: indata = tmp_filename()
30
sage: f = open(indata, "w")
31
sage: f.write("17\n42\n")
32
sage: f.close()
33
sage: l = read_data(indata, ZZ); l
34
[17, 42]
35
sage: f = open(indata, "w")
36
sage: f.write("1.234\n5.678\n")
37
sage: f.close()
38
sage: l = read_data(indata, RealField(17)); l
39
[1.234, 5.678]
40
"""
41
fp = open(f,"r")
42
l = []
43
while True:
44
s = fp.readline()
45
s = s.rstrip()
46
if s == '':
47
break
48
l.append(t(s))
49
fp.close()
50
return l
51
52