Saving variable value to a file does not work!!!!
h.jehadalwan at student.kun.nl
Sat Oct 6 17:42:46 CEST 2001
Alright John, now it works.
Thanks a lot.
John Roth wrote:
> "Gerhard Häring" <gh_pythonlist at gmx.de> wrote in message
> news:mailman.1001867134.25402.python-list at python.org...
> > 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)
> > > 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 "./script.py", 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.
> Print is for formatted output that is intended to be read by people
> (usually programmers.) Write is for output that is intended to be read back
> by a program.
> When you're writing to a file, you want to be able to read it back, right?
> If the system converted integers to strings, then you would need to put
> delimiters and all sorts of other stuff onto the file to be able to parse it
> when you read it. That's what Basic did, and anybody who works in
> that language can tell you exactly how ugly it gets.
> I'd much rather have the virtue of simplicity - what's on disk is exactly
> what I have in memory. Period. When I write a line, I want it read back
> the same way, and if that means that all I can write is strings, then so be
> > Gerhard
> > --
> > mail: gerhard <at> bigfoot <dot> de registered Linux user #64239
> > web: http://www.cs.fhm.edu/~ifw00065/ 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
More information about the Python-list