使用Regex将文件转为Base64并替换字符串时遇TypeError求助
解决Base64编码内容替换字符串时的TypeError问题
错误原因
base64.b64encode()返回的是bytes类型对象,而re.sub()的替换值参数要求必须是字符串类型,类型不匹配直接触发了TypeError。
修正方案
将Base64编码得到的bytes对象解码为UTF-8格式的字符串即可,使用decode('utf-8')方法完成转换。
完整修正代码
import re import base64 file = "test.txt" with open(file, "r") as f: # 读取文件内容→转bytes→Base64编码→解码为字符串 encoded_file = base64.b64encode(f.read().encode("utf-8")).decode("utf-8") string = "string" pattern = "pattern" updt_str = re.sub(pattern, encoded_file, string)
关键步骤说明
f.read().encode("utf-8"):把文件读取的字符串转为bytes格式,满足Base64编码的输入要求base64.b64encode(...).decode("utf-8"):将Base64编码后的bytes对象转换为字符串,适配re.sub()的参数类型要求
内容的提问来源于stack exchange,提问作者Antonio Costa
相关产品推荐
相关产品推荐

