正如您在评论中提到的,您要自己创建字典,因此以痛苦的
.txt格式存储字典并不是一个好主意,Python提供了一个称为“
Pickle保存内部任何对象”的库,使用pickle非常简单。
import pickle#importing the modulefavorite_color = { "Python": "interpreted", "C": "compiled" }#Initializing a Dictionary (or any Python Object)pickle.dump( favorite_color, open( "save.p", "wb" ) )#Saving the Python object in a .p (pickle file)#Loading the Python object from the Pickle file.favorite_color = pickle.load( open( "save.p", "rb" ) )您可以在此模块的帮助下保存任何Python对象(嵌套的或简单的),并在以后需要时访问其值。



