简体   繁体   中英

python, post binary data from python2 to python3

I need to post some data to server from a binary file AmbientTemp.dat , and there is python2:

import urllib
import urllib2

fp = 'xxx/AmbientTemp.dat'
with open(fp, 'rb') as fo:
    ambient = fo.read(64)
data = urllib.urlencode({
    'action': 'xxx',
    'ambient': ambient,
})
req = urllib2.Request('http://xxx', data=data)
urllib2.urlopen(req)

At first, I can save the data by python2:

class AmbientView(xxx):
    def post(self, *args, **kwargs):
        ambient = self.request.POST.get('ambient', '')
        fp = 'xxx/AmbientTemp.dat'
        with open(fp, 'wb') as fo:
            fo.write(ambient)
        ...

But it is error in python3.5:

...fo.write(ambient)
TypeError: a bytes-like object is required, not 'str'

So, I encode the str data:

fo.write(ambient.encode(encoding='utf-8'))

But the AmbientTemp.dat become 78 bit, I just read(64) .

我尝试使用latin1编码数据,并获取正确的数据。

fo.write(ambient.encode(encoding='latin1'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM