Saving variable value to a file does not work!!!!

Gerhard Häring gh_pythonlist at
Sun Sep 30 16:23:31 CEST 2001

On Sun, Sep 30, 2001 at 06:04:33PM +0200, Husam wrote:
> Hi friends,
> Im  a newbie and trying to save the value of variable 'counter' to a
> file, but it does not work.
> The code Im usig is:
> for line in lines:                # I'm reading from file: test2.txt.
> One of it's lines contain: ID 5.
>     string.split(line)
>     if line[0:2]=='ID':
>         counter=int(line[3])
>         output=open('test2.txt','a') # Hier Im opening the same file for
> append.
>         output.write(counter +1)            # This is the trouble making
> line!
> output.close()

Btw. the string.split(line) doesn't do anything in your case, if you
want to store the output of the split function, you can use something
like "mylist = string.split(line)". But now the the real problem.
> The error message I get when this code is run:
> Traceback (innermost last):
>   File "./", line 23, in ?
>     output.write(counter+1)
> TypeError: read-only buffer, int

You can't write any ints with the write function. But you can write
strings. Just do 

    output.write(str(counter + 1))

I acknowledge this is a bit strange. And I also don't know the reason
why the conversion to string doesn't happen automatically, like with the
print statement.
mail:   gerhard <at> bigfoot <dot> de       registered Linux user #64239
web:    OpenPGP public key id 86AB43C0
public key fingerprint: DEC1 1D02 5743 1159 CD20  A4B6 7B22 6575 86AB 43C0
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))

More information about the Python-list mailing list