[Tutor] triple-nested for loop not working

ALAN GAULD alan.gauld at btinternet.com
Thu May 5 01:56:41 CEST 2011


CC'd to list

 > Thanks for your suggestions. I now see I was using far too much unnecessary 
> code plus data structures (lists) that were useless. I modified the entire 
> program to the following lines based on suggestions from yourself and 
> other people on the mailing list: 


> import os, string   

you don't use either os or string, so you can lose the import line

> motif_file = open('myfolder/pythonfiles/final motifs_11SGLOBULIN', 'r')   
> align_file = open('myfolder/pythonfiles/11sglobulin.seqs', 'a+')

Here is where I think the problem occurs.
Do you really want to append your output to the end of the align file?
Or do you want to overwrite the old content with the new?

In either case the problem with opening in append  mode is that 
the file cursor is at the end of the file. So...

> finalmotifs = motif_file.readlines()
> seqalign = align_file.readlines()

I suspect seqalign is empty - check with a print statement to see....


for line in seqalign:

and if seqalign is empty nothing else gets executed...

   for item in finalmotifs:
       if item in line:
           newline = line.replace(item, '$' * len(item))
           align_file.writelines(newline)

motif_file.close() 
align_file.close() 

If you use the with statement you can dospense with the closes.
Alternatively try:

 finalmotifs = open('myfolder/pythonfiles/final motifs_11SGLOBULIN', 
'r').readlines()
seqalign = open('myfolder/pythonfiles/11sglobulin.seqs', 'r').readlines()
with open('myfolder/pythonfiles/11sglobulin.seqs', 'a') as align_file:
       for line in seqalign:
           # as before

HTH,

Alan G.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110505/a07836c6/attachment-0001.html>


More information about the Tutor mailing list