在Python Pickle 檔案中儲存並載入多個物件
要將多個物件儲存在pickle 檔案中,請依照下列步驟操作:
<code class="python">import pickle # Create a list of objects to be saved objects_to_save = [object1, object2, ...] # Open a binary file for writing with open('my_pickle_file', 'wb') as file: # Pickle each object and write it to the file for obj in objects_to_save: pickle.dump(obj, file)</code>
從pickle 檔案載入多個物件:
<code class="python"># Open the binary file for reading with open('my_pickle_file', 'rb') as file: # Load and print each object from the file while True: try: obj = pickle.load(file) print(obj) except EOFError: break</code>
其他注意事項:
以上是如何在 Python Pickle 檔案中保存和載入多個物件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!