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)
196
174
def write(self, to_file):
197
175
"""Write stanza to a file"""
198
176
to_file.writelines(self.to_lines())
246
224
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.
269
227
stanza = Stanza()
271
229
accum_value = None
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:
278
if line is None or line == '':
230
for line in line_iter:
231
if line == None or line == '':
279
232
break # end of file
281
234
break # end of stanza
282
assert line.endswith('\n')
235
line = line.decode('utf-8')
236
assert line[-1] == '\n'
284
238
if line[0] == '\t': # continues previous value
292
246
colon_index = line.index(': ')
293
247
except ValueError:
294
raise ValueError('tag/value separator not found in line %r'
248
raise ValueError('tag/value separator not found in line %r' % real_l)
296
249
tag = str(line[:colon_index])
297
250
assert valid_tag(tag), \
298
251
"invalid rio tag %r" % tag
299
252
accum_value = line[colon_index+2:-1]
301
253
if tag is not None: # add last tag-value
302
254
stanza.add(tag, accum_value)