<div dir="ltr">Thank you Peter. It works.<div><br></div><div>Best wishes,</div><div><br></div><div>Mic</div></div><div class="gmail_extra"><br><div class="gmail_quote">On Tue, Dec 15, 2015 at 1:08 AM, Peter Cock <span dir="ltr"><<a href="mailto:p.j.a.cock@googlemail.com" target="_blank">p.j.a.cock@googlemail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><span class="">On Mon, Dec 14, 2015 at 9:50 AM, Mic <<a href="mailto:mictadlo@gmail.com">mictadlo@gmail.com</a>> wrote:<br>
> Hello,<br>
><br>
> I run MACS2 to find out were peaks are located (see attached).<br>
> I wrote a script (see attached) which:<br>
><br>
> read the peaks information<br>
> extract the sequence from genome.fasta with help of the peak information<br>
> the extracted sequences are saved in a new FASTA file.<br>
><br>
> The MACS_peaks.csv file contains a column fold_enrichment and the script<br>
> safe this information in peak.fold_enrichment.<br>
><br>
> How is it possible to sort the output sequences with highest<br>
> peak.fold_enrichment?<br>
<br>
</span>You are building a list of SeqRecord objects in memory, so you<br>
would want to sort that before passing it to SeqIO.write.<br>
<br>
e.g. Right now your code does something like this:<br>
<span class=""><br>
records = [] # list of SeqRecord to be written<br>
for record in SeqIO.parse(open(fasta_file_name, "rU"), "fasta"):<br>
</span>    if ...:<br>
        records.append(SeqRecord(...))<br>
SeqIO.write(records, out_file, "fasta")<br>
<br>
<br>
<br>
The easiest way to sort the records would be to make a list<br>
of tuples (score, SeqRecord) which you can then sort. Then<br>
once sorted, pull out just the SeqRecord objects for output.<br>
<br>
<br>
score_and_records = []  # list of (score, record)<br>
<span class="">for record in SeqIO.parse(open(fasta_file_name, "rU"), "fasta"):<br>
</span>    if ...:<br>
        score_and_records.append((peak.fold_enrichment, SeqRecord(...)))<br>
# This will sort by score since that is first in the tuples:<br>
score_and_records.sort()<br>
records = [record for (score, record) in score_and_records]<br>
SeqIO.write(records, out_file, "fasta")<br>
<br>
<br>
Does that make sense?<br>
<span class="HOEnZb"><font color="#888888"><br>
Peter<br>
</font></span></blockquote></div><br></div>