First of all, readlines
reads all the lines of the file, returning them in a list. But since you only want the second line, you don’t have to read them all:
with open(arqfasta) as leitura, open(arqali, 'w') as saida:
next(leitura) # ignora a primeira linha
linha2 = next(leitura).rstrip('\r\n') # lê a segunda linha
Like an archive is eternal, when calling next
i get the next "item" from an iterable (which in the case of the file, will be the next line). That is, the first time I get the first line (and as I am not keeping this value in any variable, the same is ignored) and the second time I get the second line, which is what you want.
I used rstrip
to remove the line break from the end (since that’s why your output typed the asterisk on another line, because line breaks are also returned from reading). And I also used with
to open the file, so it will already be closed automatically.
Finally, you can write to another file using the same with
:
with open(arqfasta) as leitura, open(arqali, 'w') as saida:
next(leitura)
linha2 = next(leitura).rstrip('\r\n')
saida.write(f'>P1;pep{i}\n')
saida.write(f'sequence:pep{i}:::::::0.00: 0.00 \n')
saida.write(f'{linha2}*')
I used f-string to format the output (available from Python 3.6), so you avoid concatenating strings. If you are using a version earlier than 3.6, you can use format
:
with open(arqfasta) as leitura, open(arqali, 'w') as saida:
next(leitura)
linha2 = next(leitura).rstrip('\r\n')
saida.write('>P1;pep{}\n'.format(i))
saida.write('sequence:pep{}:::::::0.00: 0.00 \n'.format(i))
saida.write('{}*'.format(linha2))
If you want any line (not necessarily the second one), you can generalize the solution using the itertools.islice
:
from itertools import islice
n_linha = 5 # obter a quinta linha
with open(arqfasta) as leitura, open(arqali, 'w') as saida:
try:
linha2 = next(islice(leitura, n_linha - 1, n_linha)).rstrip('\r\n')
saida.write('>P1;pep{}\n'.format(i))
saida.write('sequence:pep{}:::::::0.00: 0.00 \n'.format(i))
saida.write('{}*'.format(linha2))
except StopIteration:
print(f'arquivo não tem {n_linha} linhas')