📜  如何在Python中从文件中读取字典?

📅  最后修改于: 2022-05-13 01:54:22.677000             🧑  作者: Mango

如何在Python中从文件中读取字典?

Python中的字典是键值对的集合,其中键始终是唯一的,并且通常我们需要存储字典并再次读取它。

我们可以通过 3 种方式从文件中读取字典:

  1. 使用json.loads()方法:将有效字典的字符串转换为 json 形式。
  2. 使用ast.literal_eval()方法:函数比 eval函数更安全,也可用于字典以外的所有数据类型的相互转换。
  3. 使用pickle.loads()方法:如果文件被序列化为字符流,我们也可以使用 Pickle 模块。

输入文件:

方法 1:使用json.loads()

# importing the module
import json
  
# reading the data from the file
with open('dictionary.txt') as f:
    data = f.read()
  
print("Data type before reconstruction : ", type(data))
      
# reconstructing the data as a dictionary
js = json.loads(data)
  
print("Data type after reconstruction : ", type(js))
print(js)

输出 :

Data type before reconstruction :  
Data type after reconstruction :  
{'Name': 'John', 'Age': 21, 'Id': 28}

方法 2:使用ast.literal_eval()

# importing the module
import ast
  
# reading the data from the file
with open('dictionary.txt') as f:
    data = f.read()
  
print("Data type before reconstruction : ", type(data))
      
# reconstructing the data as a dictionary
d = ast.literal_eval(data)
  
print("Data type after reconstruction : ", type(d))
print(d)

输出 :

Data type before reconstruction :  
Data type after reconstruction :  
{'Name': 'John', 'Age': 21, 'Id': 28}

方法3:我们可以使用Pickle模块达到同样的目的,但是这种方法只有在文件被序列化为字符流而不是文本格式时才有效。要了解有关Python中酸洗的更多信息,请单击此处

# importing the module
import pickle
  
# opening file in write mode (binary)
file = open("dictionary.txt", "wb")
  
my_dict = {"Name": "John",
           "Age": 21,
           "Id": 28}
  
# serializing dictionary 
pickle.dump(my_dict, file)
  
# closing the file
file.close()
  
# reading the data from the file
with open('dictionary.txt', 'rb') as handle:
    data = handle.read()
  
print("Data type before reconstruction : ", type(data))
  
# reconstructing the data as dictionary
d = pickle.loads(data)
  
print("Data type after reconstruction : ", type(d))
print(d)

输出 :

Data type before reconstruction :  
Data type after reconstruction :  
{'Name': 'John', 'Age': 21, 'Id': 28}