Insert character at a fixed position of lines

castironpi castironpi at gmail.com
Sun Jul 27 01:20:21 EDT 2008


On Jul 26, 10:02 pm, alex23 <wuwe... at gmail.com> wrote:
> Ugh, and in pointing our your inaccurate code I posted my own:
>
> > >>> f = open('dummy.txt','w')
> > >>> f.write(line = 'this doesn't work')
>
> >   File "<stdin>", line 1
> >     f.write(line = 'this doesn't work')
> >                                ^
> > SyntaxError: invalid syntax
>
> That should be:
>
> >>> f.write(line = "this doesn't work")
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: write() takes no keyword arguments
>
> Sorry about that :)

This is close.

import os
size= os.path.getsize( 'test line_insertion.txt' )
f= open( 'test line_insertion.txt', 'r+' )
linelen= len( f.readline( ) )
f.seek( 20, os.SEEK_SET )
while f.tell( )< size:
    f.write( 'y' )
    f.seek( linelen, os.SEEK_CUR )
f.flush( )
f.close( )

It assumes lines are a constant length (big assumption), and skips one
line's length of characters starting from the 20th character.  It
repeats until current file position is past the original length of the
file.



More information about the Python-list mailing list