Python文件读取行以endswith开头并移至列表[关闭]

问题描述 投票:-5回答:1

我有如下文件:

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

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

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

 [["line1 contents", "line2 contents", "line3 contents"],
  ["line4 contents", "line5 contents"],
  ["line6 contents", "line7 contents"]]
python python-2.7
1个回答
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']]

© www.soinside.com 2019 - 2024. All rights reserved.