VOOZH about

URL: https://www.geeksforgeeks.org/python/serialize-and-deserialize-an-open-file-object-in-python/

⇱ Serialize and Deserialize an Open File Object in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Serialize and Deserialize an Open File Object in Python

Last Updated : 23 Jul, 2025

Serialization refers to the process of converting an object into a format that can be easily stored or transmitted, such as a byte stream. Deserialization, on the other hand, involves reconstructing the object from its serialized form. When dealing with file operations, it's common to serialize data before writing it to a file and deserialize it when reading it back. In this article, we'll explore how to serialize and deserialize an open file object in Python.

Serialize and Deserialize an Open File Object in Python

Below are the ways to Serialize and Deserialize an Open File Object in Python:

  • Using Pickle
  • Using JSON
  • Using YAML

Serialize and Deserialize an Open File Object Using Pickle

This Python code serializes a dictionary `data` into a binary file named 'data.pickle' using the Pickle module, then deserializes it back into `loaded_data` from the same file, printing the result.


Output
Type of serialized data: <class 'bytes'>

Deserialized data: {'name': 'John', 'age': 30}
Type of deserialized data: <class 'dict'>

Serialize and Deserialize an Open File Object Using JSON

This Python script serializes a dictionary `data` into a JSON file named 'data.json', then deserializes it back into `loaded_data` from the same file, printing the result.


Output
Type of serialized data: <class 'str'>

Deserialized data: {'name': 'John', 'age': 30}
Type of deserialized data: <class 'dict'>

Serialize and Deserialize an Open File Object Using YAML

This Python script serializes a dictionary `data` into a YAML file named 'data.yaml', then deserializes it back into `loaded_data` from the same file, printing the result.

Output

Type of serialized data: <class 'str'> 
Deserialized data: {'age': 30, 'name': 'John'}
Type of deserialized data: <class 'dict'>
Comment