This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Converting fasta file into list with names and sequences
 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

can you post the example output format you want?

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?)

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

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

1 answer

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

thank you very much, it worked! :)

Glad to help.

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

Log in to answer this question.