import hashlib
string = "123456"
m = hashlib.md5() # 创建md5对象
str_bytes = string.encode(encoding='utf-8')
print(type(str_bytes))
<class 'bytes'>
m.update(str_bytes) # update方法只接收bytes类型数据作为参数
str_md5 = m.hexdigest() # 得到散列后的字符串
print('MD5散列前为 :' + string)
MD5散列前为 :123456
print('MD5散列后为 :' + str_md5)
MD5散列后为 :e10adc3949ba59abbe56e057f20f883e
f = open('data', 'wb')
text = '二进制写文件'
text_bytes = text.encode('utf-8')
f.write(text_bytes)
f.close()
f = open('data', 'rb')
data = f.read()
print(data, type(data))
b'\xe4\xba\x8c\xe8\xbf\x9b\xe5\x88\xb6\xe5\x86\x99\xe6\x96\x87\xe4\xbb\xb6' <class 'bytes'>
str_data = data.decode('utf-8')
print(str_data)
f.close()
二进制写文件
import socket
url = 'www.baidu.com'
port = 80
创建TCP socket:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
连接服务端
sock.connect((url, port))
创建请求消息头
request_url = 'GET /article-types/6/ HTTP/1.1\r\nHost: www.zhangdongshengtech.com\r\nConnection: close\r\n\r\n'
print(request_url)
GET /article-types/6/ HTTP/1.1 Host: www.zhangdongshengtech.com Connection: close
发送请求:
sock.send(request_url.encode())
response = b''
接收返回的数据:
rec = sock.recv(1024)
while rec:
response += rec
rec = sock.recv(1024)
print(response.decode())
HTTP/1.1 403 Forbidden Server: bfe Date: Thu, 17 Apr 2025 06:14:30 GMT Content-Length: 0 Content-Type: text/plain; charset=utf-8 Connection: close
print(type(response))
<class 'bytes'>
string = "爱我中华"
bstr = string.encode(encoding='utf-8')
print(bstr, type(bstr))
b'\xe7\x88\xb1\xe6\x88\x91\xe4\xb8\xad\xe5\x8d\x8e' <class 'bytes'>
string = bstr.decode(encoding='utf-8')
print(string, type(string))
爱我中华 <class 'str'>