171
171
"""Return stanza as a single string"""
172
172
return ''.join(self.to_lines())
174
def to_unicode(self):
175
"""Return stanza as a single Unicode string.
177
This is most useful when adding a Stanza to a parent Stanza
183
for tag, value in self.items:
185
result.append(tag + ': \n')
187
# don't want splitlines behaviour on empty lines
188
val_lines = value.split('\n')
189
result.append(tag + ': ' + val_lines[0] + '\n')
190
for line in val_lines[1:]:
191
result.append('\t' + line + '\n')
193
result.append(tag + ': ' + value + '\n')
194
return u''.join(result)
174
196
def write(self, to_file):
175
197
"""Write stanza to a file"""
176
198
to_file.writelines(self.to_lines())
224
246
The raw lines must be in utf-8 encoding.
248
unicode_iter = (line.decode('utf-8') for line in line_iter)
249
return read_stanza_unicode(unicode_iter)
252
def read_stanza_unicode(unicode_iter):
253
"""Read a Stanza from a list of lines or a file.
255
The lines should already be in unicode form. This returns a single
256
stanza that was read. If there is a blank line at the end of the Stanza,
257
it is consumed. It is not an error for there to be no blank line at
258
the end of the iterable. If there is a blank line at the beginning,
259
this is treated as an empty Stanza and None is returned.
261
Only the stanza lines and the trailing blank (if any) are consumed
262
from the unicode_iter
264
:param unicode_iter: A iterable, yeilding Unicode strings. See read_stanza
265
if you have a utf-8 encoded string.
266
:return: A Stanza object if there are any lines in the file.
227
269
stanza = Stanza()
229
271
accum_value = None
230
for line in line_iter:
273
# TODO: jam 20060922 This code should raise real errors rather than
274
# using 'assert' to process user input, or raising ValueError
275
# rather than a more specific error.
277
for line in unicode_iter:
231
278
if line is None or line == '':
232
279
break # end of file
234
281
break # end of stanza
235
line = line.decode('utf-8')
236
assert line[-1] == '\n'
282
assert line.endswith('\n')
238
284
if line[0] == '\t': # continues previous value
246
292
colon_index = line.index(': ')
247
293
except ValueError:
248
raise ValueError('tag/value separator not found in line %r' % real_l)
294
raise ValueError('tag/value separator not found in line %r'
249
296
tag = str(line[:colon_index])
250
297
assert valid_tag(tag), \
251
298
"invalid rio tag %r" % tag
252
299
accum_value = line[colon_index+2:-1]
253
301
if tag is not None: # add last tag-value
254
302
stanza.add(tag, accum_value)