解決python3 UnicodeDecodeError: 'gbk' codec can't decode byte


本來想寫個html來玩玩,結果讀取文件得時候就BUG了。。。。

以下代碼讀取html中無中文沒有問題。

def handle_request(client):
    buf = client.recv(1024)
    client.send(b"HTTP/1.1 200 OK\r\n\r\n")
    with open ('index.html','r') as f:
        data = f.read()
    data=data.encode(encoding="utf8")
    #print(type(data))
    client.send(data)

 

添加中文。

報錯信息如下:

UnicodeDecodeError: 'gbk' codec can't decode byte 0xa0 in position 121: illegal multibyte sequence

解決方法:

把 open 的方式變為 二進制  with open ('index.html','rb') as f:

 

import  socket


def handle_request(client):
    buf = client.recv(1024)
    client.send(b"HTTP/1.1 200 OK\r\n\r\n")
    with open ('index.html','rb') as f: data = f.read().decode('utf-8') data=data.encode(encoding="utf8")
    #print(type(data))
    client.send(data)

def main():
    s = socket.socket()
    s.bind(("localhost",9999))
    s.listen(5)

    while True:
        connection,address = s.accept()
        handle_request(connection)
        connection.close()

if __name__ == '__main__':
    main()

 

參考 decode 和 encode的用法:

http://blog.chinaunix.net/uid-27838438-id-4227131.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM