Python path and append

Peter Otten __peter__ at web.de
Mon Apr 25 17:38:10 EDT 2016


Random832 wrote:

> 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.

You can leave the details to python though:

$ cat sample.txt
alpha
beta
gamma
$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import fileinput
>>> for line in fileinput.input("sample.txt", inplace=True):
...     print line.rstrip("\n"), "*"
... 
>>> 
$ cat sample.txt 
alpha *
beta *
gamma *

Too much magic for my taste, but the OP might like it.




More information about the Python-list mailing list