【发布时间】:2013-05-05 00:48:52
【问题描述】:
我正在寻找一种很好的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,但它看起来很笨拙。在 cmets 中,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)
如果您可以一次读取整个文件,这可以正常工作。我想知道是否有任何内置函数可以处理这个问题,或者是否有人有任何其他建议。
【问题讨论】:
标签: python io line-breaks readlines