Python path and append

Random832 random832 at fastmail.com
Mon Apr 25 16:28:32 EDT 2016


On Mon, Apr 25, 2016, at 16:15, Seymore4Head wrote:
> Thanks for the tip.
> 
> Still broke.  :(
> 
> f = open('wout.txt', 'r+')
> for line in f:
>     if line=="":
>         exit
>     line=line[:-1]
>     line=line+" *"
>     f.write(line)
>     print line
> f.close()

Your problem is that after you read the first line, your file "cursor"
is positioned after the end of that line. So when you write the modified
version of the line, it ends up after that. And then when you write it,
the cursor is wherever the end of that is.

So if you start with this:
AAA
BBB
CCC

You'll end up with this:
AAA
AAA* [this overwrites "BBB_C" with "AAA*_" if _ is the line break]
CC
CC*

There's no good way around this. You can either read the whole file into
memory at once into a list, then rewind (look at the seek function) and
write the lines out of the list, or you can write to a *different* file
than the one you're reading.



More information about the Python-list mailing list