1
2
3 """
4 A tool set for reading all kinds of output/input/data.
5
6 Author: R. Lombaert
7
8 """
9
10 from cc.tools.io import DataIO
11
12
14
15 '''
16 The Reader class.
17
18 Inherits from the builtin dictionary class, and thus functions much like a
19 dictionary. For now, no base methods from dict are overwritten.
20
21 Reader functions primarily as a final stop before the dict class is called.
22 Any Reader objects must inherit from this (directly or indirectly).
23
24 Can read in the data/input/outputfiles that are given to this class and
25 store them.
26
27 Classes inheriting from Reader usually implement their own read and write
28 methods, but some basic capabilities are available here.
29
30 '''
31
33
34 '''
35 Initialize an Reader object by setting the contents dict.
36
37 Additional args & kwargs passed to __init__ are passed to dict __init__.
38
39 @param fn: The filename of the file that is being read.
40 @type fn: str
41
42 '''
43
44
45 super(Reader,self).__init__(*args,**kwargs)
46
47
48 self['fn'] = str(fn)
49 self.fn = self['fn']
50
51
52 self['contents'] = dict()
53
54
55
56 - def readFile(self,wildcard='*',*args,**kwargs):
57
58 '''
59 Read a filename and store its contents in the Reader object.
60
61 The contents are stored in a dictionary, with the filename as key. Note
62 that one filename can refer to multiple files with the use of a wildcard
63 character. This character can be replaced upon calling this method.
64
65 The contents can be returned with the method getFile.
66
67 If the file is not found, an empty list is stored instead.
68
69 Additional args/kwargs are passed to DataIO.readFile (such as delimiter
70 and replace_spaces)
71
72 @keyword wildcard: if a wildcard character is present in the filename,
73 it can be replaced here.
74
75 (default: '*')
76 @type wildcard: string
77
78 '''
79
80
81 fn = self.fn.replace('*',wildcard)
82
83
84 self['contents'][fn] = DataIO.readFile(fn,*args,**kwargs)
85
86
87
88 - def getFile(self,wildcard='*',*args,**kwargs):
89
90 '''
91 Return the contents of the file of this Reader instance.
92
93 Wildcard characters can be replaced.
94
95 Additional keywords can be passed to the readFile method in case the
96 file was not read yet.
97
98 @keyword wildcard: if a wildcard character is present in the filename,
99 it can be replaced here.
100
101 (default: '*')
102 @type wildcard: string
103
104 @return: a list of lines in the file, each line represented by a list
105 of strings, which were seperated by the chosen delimiter, if
106 applicable.
107 @rtype: list
108
109 '''
110
111
112 fn = self.fn.replace('*',wildcard)
113
114
115 if not self['contents'].has_key(fn):
116 self.readFile(wildcard,*args,**kwargs)
117
118 return self['contents'][fn]
119