我正在尝试对用户名'进行编码将变量写入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对变量进行编码的所有方法,但没有一种方法有效。
答案 0 :(得分:0)
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
btw:file是保留关键字,不应该用作变量。