From: Vamsi on
I am trying to count the number of lines in a file and insert into
the file but getting the error message "TypeError: must be string or
read-only character buffer, not int", Could you please help me how to
correct this?


here is the code

lines1 = sum(1 for line in open('C:/test1.txt'))
wfile = open('C:/test1.txt'', 'a')
wfile.write(str(lines1).zfill(9))
wfile.close()

Thanks.
From: Stefan Schwarzer on
Hi Vamsi,

On 2010-08-13 22:50, Vamsi wrote:
> I am trying to count the number of lines in a file and insert into
> the file but getting the error message "TypeError: must be string or
> read-only character buffer, not int", Could you please help me how to
> correct this?

Which Python version do you use?

For which statement exactly do you get the message?

> here is the code
>
> lines1 = sum(1 for line in open('C:/test1.txt'))
> wfile = open('C:/test1.txt'', 'a')

You have two quotes here after the filename. These give a
SyntaxError here. Python sees two concatenated strings,
"C:/test1.txt" and ", " and stumbles over the a immediately
after the closing quote of the second string.

> wfile.write(str(lines1).zfill(9))
> wfile.close()

If I remove the redundant quote character and substitute
filenames appropriate for my system, everything works.

Maybe the code you included in this post isn't the same
which led to the error?

Stefan
From: Steven D'Aprano on
On Fri, 13 Aug 2010 13:50:48 -0700, Vamsi wrote:

> I am trying to count the number of lines in a file and insert into the
> file but getting the error message "TypeError: must be string or
> read-only character buffer, not int", Could you please help me how to
> correct this?
>
>
> here is the code
>
> lines1 = sum(1 for line in open('C:/test1.txt'))
> wfile = open('C:/test1.txt'', 'a')
> wfile.write(str(lines1).zfill(9))
> wfile.close()

No, that ISN'T the code you are using.

Don't re-type the code (introducing syntax errors), but copy and paste
WORKING code. Also you need to copy and paste the EXACT error message you
get, not just paraphrasing it.

When I correct the obvious errors in your code above, it works for me:

>>> f = open('test', 'w')
>>> f.write('hello\nworld\n')
12
>>> f.close()
>>> lines1 = sum(1 for line in open('test'))
>>> wfile = open('test', 'a')
>>> wfile.write(str(lines1).zfill(9))
9
>>> wfile.close()

and the file is correctly updated:

>>> open('test').read()
'hello\nworld\n000000002'


--
Steven