How do I encode/decode a dictionary in Python 3 to

2019-08-01 16:10发布

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()

3条回答
Ridiculous、
2楼-- · 2019-08-01 16:51

The typical thing to use here is either the json or pickle modules (both in the standard library). The process is called "serialization". pickle can serialize almost arbitrary python objects whereas json can only serialize basic types/objects (integers, floats, strings, lists, dictionaries). json is human readible at the end of the day whereas pickle files aren't.

查看更多
smile是对你的礼貌
3楼-- · 2019-08-01 16:53

An alternative to encoding/decoding is to simply use a file as a dict, and python has the shelve module which does exactly this. This module uses a file as database and provide a dict-like interface to it.

It has some limitations, for example keys must be strings, and it's obviously slower than a normal dict since it performs I/O operations.

查看更多
不美不萌又怎样
4楼-- · 2019-08-01 17:12

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()
查看更多
登录 后发表回答