问题:编写一个 Python 程序,允许用户使用 pickle 模块在文件中存储对象列表。然后,创建第二个程序,读取并反序列化 pickle 文件中的数据,并将其显示在控制台中。
解决方案:
# Pickling Program (Save to File)
import pickle
# List of objects to save
data_to_pickle = [1, "Hello, World!", {"Python": 3.9, "Library": "pickle"}]
# Name of the file where the list will be saved
pickle_file = "data.pkl"
# Save the list to the pickle file
with open(pickle_file, 'wb') as file:
pickle.dump (data_to_pickle, file)
print ("Data saved successfully to", pickle_file)
# Unpicking Program (Read from File)
# Load the data from the pickle file
with open(pickle_file, 'rb') as file:
loaded_data = pickle. load(file)
print ("Data loaded from", pickle_file)
print ("File content:", loaded_data)

本问题涉及 Python 中 pickling和 unpickling 的概念,即对象的序列化和反序列化。了解如何使用 pickle 模块高效地存储和检索数据非常重要。
此外,您还需要了解如何在 Python 中处理文件。本问题属于中等难度,因为它涉及多个概念,需要预先了解 Python 中的数据结构和文件处理。