Python学习——2.base64的编码encode()出错:TypeError: a bytes-like object is required, not 'str'

先上第一次的代码:

import base64

# 字典文件路径
dic_file_path = 'C:/Users/muzi/Downloads/271_b790fbaa9f8480532fff81553e908114d783bc30/10_million_password_list_top_100.txt'
with open(dic_file_path, 'r') as f:
    password_dic = f.readlines()

username = "admin" # 用户名
for password in password_dic:
    encodestr = base64.b64encode("admin:" + password.strip())
    print(encodestr)

以上是我做题时第一次的base64编码:但在编译的时候遇到了错误
Python学习——2.base64的编码encode()出错:TypeError: a bytes-like object is required, not 'str'_第1张图片
后来我搜索了一下,问题出在了Python3对base的编码问题中:
python3.x与Python2不一样,字符都为unicode编码,而b64encode函数的参数为byte类型,所以必须先转码。

修改后:

import base64

# 字典文件路径
dic_file_path = 'C:/Users/muzi/Downloads/271_b790fbaa9f8480532fff81553e908114d783bc30/10_million_password_list_top_100.txt'
with open(dic_file_path, 'r') as f:
    password_dic = f.readlines()

username = "admin" # 用户名
for password in password_dic:
    encodestr = base64.b64encode(("admin:" + password.strip()).encode('utf-8'))
print(encodestr)

结果为:
Python学习——2.base64的编码encode()出错:TypeError: a bytes-like object is required, not 'str'_第2张图片
b’ '代表byte的意思。我们只要再将byte转换回去就可以。

print(str(encodestr,'utf-8'))

你可能感兴趣的:(Python)