Python中将字典保存为文件并读取

总结一下Python中保存文件常用的几种方法:

直接举例说明:

d = {"the":5,"v":8,"e":4}    # 随便写一个字典

方法一:直接用Python内置的读写操作:

with open("文件名.txt",'w') as f:     # 写文件
	f.write(str(d))

with open("文件名.txt",'r') as f:     # 读文件
	line = f.read()
	dic = eval(line)

输出:
dic = {'the': 5, 'v': 8, 'e': 4}

方法二:用pickle模块:

import pickle

with open("文件名.pkl",'wb') as f:      # 写文件
    pickle.dump(d,f,pickle.HIGHEST_PROTOCOL)

with open("文件名.pkl",'rb') as f:      # 读文件
    dic = pickle.load(f) 

输出:
dic = {'the': 5, 'v': 8, 'e': 4}

方法三:用numpy模块:

import numpy as np

np.save("文件名.npy",d)           # 保存文件

dic = np.load("文件名.npy",allow_pickle = True).item()     # 加载文件

输出:
dic = {'the': 5, 'v': 8, 'e': 4}

你可能感兴趣的:(Python)