【发布时间】:2019-05-22 20:21:56
【问题描述】:
试图在 JSON 文件中转储字典给我错误“TypeError: a bytes-like object is required, not 'str'”
我已经尝试删除“encrypt_string”函数的字节转换部分,但它给了我错误“TypeError: a bytes-like object is required, not 'str'”
#!/usr/bin/python3
# Imports
import json
import base64
from cryptography.fernet import Fernet
# Save
def encrypt_string(string, f):
return str(f.encrypt(base64.b64encode(bytes(string,'utf-8'))).decode('utf-8'))
def encrypt_dict(dict):
fk = Fernet.generate_key().decode('utf-8')
f = Fernet(fk)
ed = {}
ed['fk'] = base64.b64encode(bytes(fk, 'utf-8'))
for key, value in dict.items():
ekey = encrypt_string(key, f)
evalue = encrypt_string(value, f)
ed[ekey[::-1]] = evalue[::-1]
return ed
def save_game(slot, savename):
print("Saving file...")
path = 'saves/savegame{0}.json'.format(slot)
data = {
'game': 'Game name here',
'version': 'Version here',
'author': 'Author here',
'savename': str(savename),
}
data = encrypt_dict(data)
with open(path, 'w') as f:
json.dump(data, f)
f.close()
print('Data saved in', path)
# Main
import gamemodule as gm
def main():
print("Running...")
gm.save_game(1, 'test')
input("Press any button to continue...")
我希望程序保存游戏数据的文件,但它只返回“TypeError: a bytes-like object is required, not 'str'”错误
我认为这与我在 encrypt_dict 函数中对变量进行编码有关,但我不确定,我浏览过与此类似的其他问题,但没有找到任何可以解决我的错误的问题
【问题讨论】:
-
哪一行报错?
标签: python json python-3.x encoding byte