Converting fasta file into list with names and sequences
1
0
Entering edit mode
7.0 years ago
anme • 0
 def ReadFastaFile(filename):
  fileObj = open(filename, 'r')
  sequences = []
  seqFragments = []
  for line in fileObj:
    if line.startswith('>'):
      if seqFragments:
        sequence = ''.join(seqFragments)
        sequences.append(sequence)
      seqFragments = []
    else:
      seq = line.rstrip()
      seqFragments.append(seq)
  if seqFragments:
    sequence = ''.join(seqFragments)
    sequences.append(sequence)
  fileObj.close()
  return sequences

I want to get list with name and sequence This code gives me a list with only the sequence, because i first thought i would not need the name for what I want to do. But now i realized that it would be good to also include the names. Maybe if possible also in a dictionary form, so that it is like: dict = {'name':sequence}. Does somebody have I idea how to alter the code to achieve this?

python fasta list dictionary • 9.0k views
ADD COMMENT
0
Entering edit mode

can you post the example output format you want?

ADD REPLY
0
Entering edit mode

example output (would be happy about one of both): list = [['name1','sequence1'],['name2'],['sequence2'].....]

or

dictionary = {'name1':'sequence1','name2':['sequence2'.....} (but i am not sure right no if you can have both elements as strings in a dictionary?)

ADD REPLY
1
Entering edit mode

not sure about python...but in perl i would create a hash

list = [['name1','sequence1'],['name2'],['sequence2'].....] hash = [['key1','value1'],['key2'],['value2'].....]

ADD REPLY
3
Entering edit mode
7.0 years ago

Could also be a oneliner:

from Bio import SeqIO
seq_dict = {rec.id : rec.seq for rec in SeqIO.parse("myfile.fasta", "fasta")}

If you want to learn more about what's going on in this line, read about biopython, and list and dict comprehensions

ADD COMMENT
0
Entering edit mode

thank you very much, it worked! :)

ADD REPLY
0
Entering edit mode

Glad to help.

If the answer resolved your question you should mark it as accepted.
Upvote|Bookmark|Accept

ADD REPLY

Login before adding your answer.

Traffic: 1117 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6