MMAP, "TypeError: 'str' does not support the buffer interface" | Python

f = open('C:\Python33\File.doc')
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if (s.find("blabla")) != -1:
    print("True")

When I run the following code, I get the error "TypeError: 'str' does not support the buffer interface", why is this, and what can I do to solve this problem?

I have searched online for the answer, and a common result is to do with me using Python 3 over Python 2 and they way it treats data types. But I have not found a direct answer yet.

Thanks!

Answers


strs are unicode codepoints, and they don't support the buffer interface (which basically means raw access to the memory underneath them). In general, you need to convert them into a bytes using str.encode, or in this case you can just use a bytes literal instead of a str literal by putting on a b prefix.

if s.find(b'blabla') != -1:
    ...

What Every Programmer Needs To Know About Unicode has a pretty good explanation of why you need to use encode to get the bytes. This is why Python's str doesn't provide a buffer interface - you need to explicitly tell it the encoding before it knows what bytes should be in it.


Need Your Help

PHP Zend_Paginator on mySql query using GET

php mysql zend-framework

I am trying to call pages using Zend_Paginate() on a query that loads based on a GET search string the query essentially does the following: