io - Read a file with line continuation characters in Python -
i'm looking nice pythonic way of reading file, , joining lines logical continuations of ones above, indicated line continuation character. e.g.
here normal line. line continues on \ 2 lines. line continues over\ 3 \ lines. i've found 1 solution here: http://code.activestate.com/recipes/66064-reading-lines-with-continuation-characters, seems unwieldy. there nice solution daniel wang in comments using generator:
def loglines(rawdata): lines = [] in rawdata.splitlines(): lines.append(i) if not i.endswith("\\"): yield "".join(lines) lines = [] if len(lines)>0: yield "".join(lines) this works fine, provided can read whole file @ once. wondered if there built-in functions handle this, or whether has other suggestions.
with open("data.txt") fin: line in fin: line = line.rstrip('\n') while line.endswith('\\'): line = line[:-1] + next(fin).rstrip('\n') print line ... you can pull out generator if wish
def continuation_lines(fin): line in fin: line = line.rstrip('\n') while line.endswith('\\'): line = line[:-1] + next(fin).rstrip('\n') yield line open("long.txt") fin: line in continuation_lines(fin): ...
Comments
Post a Comment