[Tutor] creating a buffer object from a file ?
alan.gauld at btinternet.com
Tue May 22 09:32:11 CEST 2007
"Iyer" <maseriyer at yahoo.com> wrote
> How do I go about creating a buffer object from
> a file containing binary data ? I have a function
> that accepts only buffer objects for it's parameters
Can you define what you mean by a buffer object?
Python uses duck typing so, unless the function has
been badly coded with an explicit type check, it
should accept any object that supports the methods
If you really do need a buffer the docs say:
Buffer objects are not directly supported by Python
syntax, but can be created by calling the builtin
function buffer(). They don't support concatenation
Which was new to me. But some experimentation
with the interpreter shows:
| buffer(object [, offset[, size]])
| Create a new buffer object which references the given object.
| The buffer will reference a slice of the target object from the
| start of the object (or at the specified offset). The slice will
| extend to the end of the target object (or with the specified
>>> b = buffer('fredrica', 2,4)
So we can see how to create a buffer object.
You want to do it with a binary file. You can read the content
of a binary file using the struct module. But you need to know
what kind of data is in your file. To create a buffer you need
a string. So do you want your buffer to process the raw binary
bytes as if they were a string? Or do you want to convert the
binary data and then convert it again into a string representation?
Either is possible but you need to decide which you need.
BTW Please don't post new subjects to the list by replying
to an existing subject. For those using threaded readers it
buries your post insife another thread, in this case 3 levels
deep in one about MSSQL! I only just noticed it. Its better
to start a fresh message. After all its not exactly difficult to
type tutor at python.org in the to line! :-)
Author of the Learn to Program web site
More information about the Tutor