python,将二进制数据从python2发布到python3

2024-06-16 11:40:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将一些数据从二进制文件AmbientTemp.dat发布到服务器,这里有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)

首先,我可以用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)
        ...

但python3.5中有一个错误:

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

所以,我对str数据进行编码:

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

但是AmbientTemp.dat变成了78位,我只是read(64)。你知道吗


Tags: 数据importdatawithopenurllib2urllibdat