Reading a file in python and sending contents to two different variables

Viewed 38

I am trying to read the file and put the two sequences (ie Spar and Sbay) into two variables seq1 and seq2. So far I only know how to pass everything to one sequence by using this code.

filename = 'AQY2.fasta'
readfile = open(filename, 'r')
seq1 = ''
seq2 = ''
for line in readfile.readlines():
     if ( line[0] == '>' ):
         header = line[1:]
     else:
         seq1 = seq1 + line

readfile.close() 
print(seq1)

Can anyone help me to read the two sequences into seq1 and seq2?

The image contains two sequences

1 Answers

I am using two vaiable matchSpar and matchSbay to read the file and seq a dictionary to store the corresponding result.

if matchSpar is set to True then lines added append to '>Spar' key in seq dictionary if matchSbay is set to True then lines added append to '>Sbay' key in seq dictionary.

filename = 'AQY2.fasta'
readfile = open(filename, 'r')
seq= {
        '>Spar' : "",
        '>Sbay' : ""
        }
matchSpar = False
matchSbay = False
lines = []
for line in readfile.readlines():
    line = line.replace('\n', '')
    if line == '>Spar':
        matchSpar = True
        matchSbay = False

    if line == '>Sbay':
        matchSpar = False
        matchSbay = True

    if matchSpar :
        seq[">Spar"] += line+"\n"
    if matchSbay :
        seq[">Sbay"] += line+"\n"

readfile.close() 

print(seq['>Spar'])
print(seq['>Sbay'])

Its recommended to use with keyword to file handling in python :

filename = 'AQY2.fasta'
seq= {
        '>Spar' : "",
        '>Sbay' : ""
        }
matchSpar = False
matchSbay = False

with open(filename, 'r') as readfile:
 for line in readfile.readlines():
    if line == '>Spar\n':
        matchSpar = True
        matchSbay = False

    if line == '>Sbay\n':
        matchSpar = False
        matchSbay = True

    if matchSpar :
        seq[">Spar"] += line
    if matchSbay :
        seq[">Sbay"] += line

print(seq['>Spar'])
print(seq['>Sbay'])
Related