Recursive insertion of a line

Henry henry.robinson at gmail.com
Tue Nov 20 01:15:16 CET 2007


On 19/11/2007, Francesco Pietra <chiendarret at yahoo.com> wrote:
>
> New to the list and just beginning with Python (Linux B console). Urgent
> problem before I can correctly program:
>
> How to insert "TER" records recursively, i.e. some thousand fold,  in a
> file
> like in the following example? "H2 WAT" is the only constant
> characteristic of
> the line after which to insert "TER"; that distinguishes also for lines
> for
> other atoms. Just to illustrate what I want to do - for those unfamiliar
> with
> this type of file - a three-line set between two "TER" defines a water
> molecule, with a set of xyz coordinates for each atom.
>

If every molecule is water, and therefore 3 atoms, you can use this fact to
insert TER in the right place. You don't need recursion:

f = open( "atoms.txt", "rt" )
lineCount = 0
for line in f.xreadlines( ):
    lineCount = lineCount + 1
    print line
    if lineCount == 3:
        lineCount = 0
        print "TER"
f.close( )

You could do the above in fewer lines with a regex (this would also work
even if all molecules weren't water), which would probably be neater, but is
left as an exercise for the reader :) There are probably much better
idiomatic ways to do this, and I defer to much more experienced Python
programmers to show you them.

HTH,

Henry
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20071120/37a11a50/attachment.html>


More information about the Python-list mailing list