Saving variable value to a file does not work!!!!
Steve Holden
sholden at holdenweb.com
Sun Sep 30 12:52:11 EDT 2001
"Husam" <husalwan at sci.kun.nl> wrote in message
news:3BB74291.CB898293 at sci.kun.nl...
> 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)
Unforunately the line above does not alter the "line" variable. Maybe what
you need is
line = string.split(line)
or it's method-based alternative (good in 2.x):
line = line.split()
However, once you have split the line, you cannot then continue to treat is
as a string, since you will have transformed it into an array of strings.
The next two statements should therefore be changed...
> if line[0:2]=='ID':
> counter=int(line[3])
if line[0] == 'ID':
counter = int(line[1])
However, the code as you have written it appears to work because you are
treating line as a string throughout, so you might equally prefer to simpy
remove the string.split(line) call, which does nothing because you don't
assign the result.
> 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()
>
>
> 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
>
This error message appears because what you are trying to write is not a
string:
>>> output = open("deleteme.txt", "a")
>>> output.write(5+1)
Traceback (innermost last):
File "<pyshell#1>", line 1, in ?
output.write(5+1)
TypeError: read-only character buffer, int
The following should work:
output.write(str(counter+1))
>>> output.write(str(5+1))
>>>
Hope this helps.
regards
Steve
--
--
http://www.holdenweb.com/
More information about the Python-list
mailing list