首页 > 解决方案 > Python文件读取行从startswith到endswith并移动到列表

问题描述

我有如下文件:

=======
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"]]

标签: pythonpython-2.7

解决方案


假设您的输入文本存储在 variable 中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']]


推荐阅读