Dave
Dave

Reputation: 1

File to list, split by newlines (python 3.5.0)

How can I convert a fasta file in python to a list, split by two newlines?

So, this is how the file looks like:

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

I need something like this, in a list:

[Subject1
Subject1
Subject1,
Subject2
Subject2
Subject2]

So, every few lines of one 'subject' should be one item together, so that I can remove or print all lines of one specific subject.

Thanks!

Upvotes: 0

Views: 176

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336078

Simple:

Read the file into memory:

text = myfile.read()

Split the text:

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

A quick demo:

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...']

Upvotes: 1

Related Questions