python使用base64进行编码解码并储存

· Special

python使用base64进行编码

#打开文件
f=open('base64','r+',encoding='utf-8')
#读取并写入
all_content=f.read()

#编码,base64接受字节并输出字节
all_content=base64.b64encode(all_content.encode('utf-8')).decode('utf-8')
print(all_content)


#写入
f.seek(0)
f.truncate()

f.write(all_content)
f.close()


python读取并解码base64,覆盖原文档

f=open('base64','r+',encoding='utf-8')

#读取文件并复原
all_content=f.read()
print(all_content)

#将内容变成字节
all_content=all_content.encode('utf-8')
print(all_content)

#内容解密出字节
all_content_base64=base64.b64decode(all_content)

#字节转utf-8文字
all_content_base64=all_content_base64.decode('utf-8')

print(all_content_base64)


#写入文件
#清空文档
f.seek(0)
f.truncate()

f.write(all_content_base64)
f.close()

python


评论