我编写了一个httpserver来为python2.7和python3.5提供html文件。
def do_GET(self):
...
#if resoure is api
data = json.dumps({'message':['thanks for your answer']})
#if resource is file name
with open(resource, 'rb') as f:
data = f.read()
self.send_response(response)
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(data) # this line raise TypeError: a bytes-like object is required, not 'str'代码在python2.7中工作,但在python 3中,它引发了上述错误。
我可以使用bytearray(data, 'utf-8')将str转换为字节,但是html在web中改变了。

我的问题:如何在不使用2-3工具和不改变文件编码的情况下支持python2和python3。
在python2和python3中,是否有更好的方式读取文件并将其内容发送给客户端?
提前谢谢。
发布于 2016-12-01 17:55:14
您只需在二进制模式下打开您的文件,而不是以文本模式打开:
with open(resource,"rb") as f:
data = f.read()然后,data是python 3中的bytes对象,在python 2中是str,它适用于这两个版本。
作为一个积极的副作用,当这段代码击中一个Windows框时,它仍然有效(否则,像图像这样的二进制文件会因为在文本模式下打开时的终止转换而损坏)。
https://stackoverflow.com/questions/40917251
复制相似问题