[Tutor] creating files with python and a thanks
Eve Kotyk
e.kotyk@shaw.ca
Tue, 19 Feb 2002 04:24:42 +0000
Thanks Danny and Sheila for your help on this.
Danny thanks for the recommended reading..and your tip on f.writelines()
will be very helpful for the next version.
E
Danny Yoo wrote:
>
> On Mon, 18 Feb 2002, Eve Kotyk wrote:
>
> > > Let's look at that error message you showed before:
> > >
> > > Traceback (innermost last):
> > > File "<pyshell#78>", line 1, in ?
> > > gather_data()
> > > File "<pyshell#75>", line 9, in gather_data
> > > f.write(output)
> > > TypeError: read-only buffer, list
> >
> > No problem but could you explain the error message a little? I
> > assumed it meant that I had variable elements of a different type
> > (such as a string and integers) but I tried the code again using only
> > strings and I still got the same error. What is a read-only buffer?
>
> Yes, that error message was confusing, and according to:
>
> http://mail.python.org/pipermail/python-dev/2000-December/010845.html
>
> the developers changed the message to make a little more sense. *grin*
> Python 2.2 gives a better error message, so let me get it to error out in
> a similar way:
>
> ###
> >>> f = open('foo.txt', 'w')
> >>> some_data = ['this is the first line', 'this is the second line']
> >>> f.write(42)
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> TypeError: argument 1 must be string or read-only character buffer, not
> int
> >>> f.write(some_data)
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> TypeError: argument 1 must be string or read-only character buffer, not
> list
> >>> f.write("ok, ok")
> >>>
> ###
>
> So f.write() likes to see only strings. By the way, if we want to write
> the contents of a bunch of strings in a list, we can use the
> f.writelines() function:
>
> http://www.python.org/doc/current/lib/bltin-file-objects.html
>
> 'Character buffer' is a low level term that's roughly a synonym for
> "string", but I believe it's actually a little broader. It's somewhat
> obscure: there's a mention of "buffers" in the documentation:
>
> http://www.python.org/doc/lib/built-in-funcs.html
>
> with the "buffer()" function, as well as some reference material in the
> Python/C API:
>
> http://www.python.org/doc/current/api/bufferObjects.html
>
> >From what I can gather: a character buffer is any object in Python that
> supports byte-oriented access, that is, stuff that's easy to write into a
> file. Buffers provide a way to get access to data in a very low-level,
> efficient manner. However, we probably won't ever need to manipulate
> buffers by hand, as the majority of "buffer" objects we run into are
> strings. I guess I'm trying to say: don't worry about character buffers.
> *grin*
>
> Hope this helps!
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
--
ekotyk
http://members.shaw.ca/e.kotyk/virtualstudio.htm