如何将Python 3中的字典编码/解码为外部文件? [英] How do I encode/decode a dictionary in Python 3 to/from an external file?
问题描述
我想知道,我将如何将Python 3中的字典解码为不可读的格式,以防止某人在程序外修改它?
同样,我怎么才能从该文件读取并将字典编码回来?
我的测试代码现在只写入和读取纯文本文件。
import ast
myDict = {}
#Writer
fileModifier = open('file.txt','w')
fileModifier.write(str(myDict)))
fileModifier.close()
#Reader
fileModifier = open('file.txt','r')
myDict = ast.literal_eval(fileModifier.read())
fileModifier.close()
根据您的字典所持有的内容,您可以使用像 json 或 pickle (用于存储我的复杂python数据结构)。
这里是一个使用json的例子来使用腌菜只需将 json
的所有实例替换为 pickle
,您应该很好去。
import json
myDict = {}
#Writer
fileModifier = open('file 。文本', ' w'):
json.dump(myDict,fileModifier)
fileModifier.close()
#Reader
fileModifier = open('file.txt',' r'):
myDict = json.load(fileModifier)
fileModifier.close()
I'm relatively new to and encoding and decoding, in fact I don't have any experience with it at all.
I was wondering, how would I decode a dictionary in Python 3 into an unreadable format that would prevent someone from modifying it outside the program?
Likewise, how would I then read from that file and encode the dictionary back?
My test code right now only writes to and reads from a plain text file.
import ast
myDict = {}
#Writer
fileModifier = open('file.txt', 'w')
fileModifier.write(str(myDict)))
fileModifier.close()
#Reader
fileModifier = open('file.txt', 'r')
myDict = ast.literal_eval(fileModifier.read())
fileModifier.close()
Depending on what your dictionary is holding you can use an encoding library like json or pickle (useful for storing my complex python data structures).
Here is an example using json, to use pickle just replace all instances of json
with pickle
and you should be good to go.
import json
myDict = {}
#Writer
fileModifier = open('file.txt', 'w'):
json.dump(myDict, fileModifier)
fileModifier.close()
#Reader
fileModifier = open('file.txt', 'r'):
myDict = json.load(fileModifier)
fileModifier.close()
这篇关于如何将Python 3中的字典编码/解码为外部文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!