Python文件读取行从开始到结束并移至列表

时间:2018-10-13 16:08:37

标签: python python-2.7

我有如下文件:

=======
line1 contents
line2 contents
line3 contents
=======
=======
line4 contents
line5 contents
=======
=======
line6 contents
line7 contents
=======

读取以=======开头的文件内容,以=======结束的文件内容。将输出发送到列表。

以下是列表列表的预期输出

 [["line1 contents", "line2 contents", "line3 contents"],
  ["line4 contents", "line5 contents"],
  ["line6 contents", "line7 contents"]]

1 个答案:

答案 0 :(得分:2)

假设输入文本存储在变量s中,则可以使用以下列表理解:

[l.splitlines() for l in s.split('=======\n')[1::2]]

使用示例输入,将返回:

[['line1 contents', 'line2 contents', 'line3 contents'], ['line4 contents', 'line5 contents'], ['line6 contents', 'line7 contents']]