要列出的文件,按换行符分割(python 3.5.0)

时间:2016-04-15 12:10:06

标签: python

如何将python中的fasta文件转换为列表,由两个换行符拆分?

所以,这就是文件的样子:

Subject1...
Subject1...
Subject1...
[Enter]
[Enter]
Subject2...
Subject2...
Subject2...

我在列表中需要这样的东西:

[Subject1
Subject1
Subject1,
Subject2
Subject2
Subject2]

因此,一个'主题'的每几行应该是一个项目,这样我就可以删除或打印一个特定主题的所有行。

谢谢!

1 个答案:

答案 0 :(得分:1)

简单:

将文件读入内存:

text = myfile.read()

Split the text

subjects = text.split("\n\n")

快速演示:

In [2]: text = """Subject1...
   ...: Subject1...
   ...: Subject1...
   ...:
   ...: Subject2...
   ...: Subject2...
   ...: Subject2...
   ...:
   ...: Subject3...
   ...: Subject3...
   ...: Subject3..."""

In [3]: text.split("\n\n")
Out[3]:
['Subject1...\nSubject1...\nSubject1...',
 'Subject2...\nSubject2...\nSubject2...',
 'Subject3...\nSubject3...\nSubject3...']