[Tutor] Read only buffer tuple ? [data structures / close()ing a file]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri May 23 00:25:13 2003


On Thu, 22 May 2003, james dean wrote:

> Hi all, I have a file writing problem.
>
> I am extracting some text from a database and opening a file to write it
> to and I get this error.
>
> f.write(msg[0])
> TypeError: read-only buffer, tuple
>
> Here is the code I am using:
>
> sql = "SELECT message FROM email WHERE emailid='%s'" % (rows[0])
> msg = con1.query(sql).getresult()
> f = open('temp','w')
> f.write(msg[0])
> f.close
>
> What am I doing wrong?


Hi James,


I'll assume for the moment that 'msg' contains a list of tuples.  A query
to an SQL database should return a "result set" list, and each element of
that result set will be itself a tuple.  The reasons for this is
consistancy; if we do the query:

    """select emailid, message from email whrere emailid=%s"""

vs.

    """select message from email whrere emailid=%s"""

the structure returned by the database layer will have the same kind of
shape.  We can take comfort that our result set will look like:

  [ row1,
    row2,
    row3,
  ]


And, even if our rows only consist of a single column, each row will
always be a tuple:

    row = (1, 'this is a test'),

vs

    row = ('this is a test',)



What we may want to do, then, is just extract the first element of the
row:


###
sql = "SELECT message FROM email WHERE emailid='%s'" % (rows[0])
result_set = con1.query(sql).getresult()
first_row = msg[0]
first_message = first_row[0]
###



Some of us may consider this verbose though; if we can safely assume that
the query is always successful, we can compress this down to:

###
sql = "SELECT message FROM email WHERE emailid='%s'" % (rows[0])
first_msg = con1.query(sql).getresult()[0][0]
###

And if not, we'll have to do some checks.




One other thing: that last statement in the program:


> f.close


is missing parentheses: without parentheses, functions don't fire off in
Python.  It might seem a little odd or verbose, but when we learn more
about Python, we can talk about why Python offers that option of naming
but not automatically activating a function.


So when we want to close a file, we use:

    f.close()

even if we don't send any parameters over.



Hope this helps!