Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PYTHON3 (and not is PYTHON2 ) TypeError: Won't implicitly convert Unicode to bytes; use .encode()

l have this function that works perfectly with python2

 def writeCache(env, cache):
        with env.begin(write=True) as txn:
            for k, v in cache.items():
                txn.put(k, v)

However when l execute it with python3.5.2 it returns the following error :

txn.put(k, v)
TypeError: Won't implicitly convert Unicode to bytes; use .encode()

First try to resolve that :

def writeCache(env, cache):
            with env.begin(write=True) as txn:
                for k, v in cache.items():
                    k.encode()

works but variable v is not included.

def writeCache(env, cache):
                with env.begin(write=True) as txn:
                    for k, v in cache.items():
                        k.encode()
                        v.encode()

l get the following :

AttributeError: 'bytes' object has no attribute 'encode'

which is related to v.encode()

like image 571
vincent75 Avatar asked Sep 07 '25 02:09

vincent75


1 Answers

txn.put(str(k).encode(), str(v).encode())

that works for me.

like image 185
Phhi7 Avatar answered Sep 09 '25 19:09

Phhi7