3

我正在寻找一种很好的pythonic方式来读取文件,并加入任何作为上述逻辑延续的行,如行继续字符所示。例如

Here is a normal line.
This line continues over  \
two lines.
This line continues over\
three \
lines.

我在这里找到了一种解决方案:http: //code.activestate.com/recipes/66064-reading-lines-with-continuation-characters,但它看起来很笨拙。Daniel Wang 在使用生成器的评论中有一个很好的解决方案:

def loglines(rawdata):
    lines = []
    for i in rawdata.splitlines():
        lines.append(i)
        if not i.endswith("\\"):
            yield "".join(lines)
            lines = []
    if len(lines)>0: yield "".join(lines)

如果您可以一次读取整个文件,这可以正常工作。我想知道是否有任何内置函数可以处理这个问题,或者是否有人有任何其他建议。

4

1 回答 1

14
with open("data.txt") as fin:
    for line in fin:
        line = line.rstrip('\n')
        while line.endswith('\\'):
            line = line[:-1] + next(fin).rstrip('\n')
        print line
        ...

如果你愿意,你也可以把它拉到发电机里

def continuation_lines(fin):
    for line in fin:
        line = line.rstrip('\n')
        while line.endswith('\\'):
            line = line[:-1] + next(fin).rstrip('\n')
        yield line


with open("long.txt") as fin:
    for line in continuation_lines(fin):
        ...
于 2013-05-10T10:48:28.920 回答