Python 正在尝试对此变量进行Base64编码

Python 正在尝试对此变量进行Base64编码,python,base64,Python,Base64,我试图将“username”变量编码为Base64,然后将其写入文本文件,最后解码Base64,并读取/打印它 while True: username = input("What is your username?: ") file = open("newfile.txt", "w") file.write(base64.b64encode(username)) file.close file = open("newfile.txt", "r") file.read(base64.b64

我试图将“username”变量编码为Base64,然后将其写入文本文件,最后解码Base64,并读取/打印它

while True:

username = input("What is your username?: ")

file = open("newfile.txt", "w")
file.write(base64.b64encode(username))
file.close

file = open("newfile.txt", "r")
file.read(base64.b64decode(username))
break
-TypeError-“str”不支持缓冲区接口

我在这里所做的似乎是我所见过的最合乎逻辑的


我对Python相当陌生,并且已经尝试了我在网上看到的所有Base64编码变量的方法,但没有一个有效。

Base64需要并返回字节(在python3中);但是字符串必须写入文件。下面是一个显式书写和更紧凑阅读的示例:

import base64

while True:

    username_str = input("What is your username?: ")

    with open("newfile.txt", "w") as file_handler:
        username_bytes = bytes(username_str, 'utf-8')
        b64_bytes = base64.b64encode(username_bytes)
        b64_str = b64_bytes.decode('utf-8')
        file_handler.write(b64_str)
        # file_handler.close()
        # close not needed inside the context handler
    with open("newfile.txt", "r") as file_handler:        
        print(base64.b64decode(bytes(file_handler.read(), 'utf-8')).decode('utf-8'))
    break

顺便说一句:file是一个保留关键字,不应用作变量。

1)您没有向该文件写入任何内容,2)没有您尝试使用base64的痕迹,也没有您遇到的特定问题。对不起,我对这一点很陌生。无论如何我已经更新了它。仅供参考:
file.read(base64.b64decode(username))
意味着使用
username
b64解码它,然后
读取
文件
@user3205119:你还没读过的东西,你无法解码!解码发生在读取之后。base64编码错误是因为在Python3中需要传递字节字符串,而不是普通的Unicode字符串。但正如其他人所说,您发布的代码还有其他各种问题,包括没有正确缩进。