如何将Python 3中的字典编码/解码为外部文件? [英] How do I encode/decode a dictionary in Python 3 to/from an external file?

查看:173
本文介绍了如何将Python 3中的字典编码/解码为外部文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相对来说比较新,编码和解码,其实我根本就没有任何经验。



我想知道,我将如何将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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆