|
| 1 | +# Serialization and Deserialization in Python |
| 2 | + |
| 3 | +Serialization in Python is the process of converting a Python object into a byte stream, which can then be easily stored or transmitted. |
| 4 | + |
| 5 | + Deserialization is the reverse process, where the byte stream is converted back into a Python object. |
| 6 | + |
| 7 | + In python, `pickle` module is used for this. |
| 8 | + |
| 9 | + - Serialization (Pickling): Converts Python objects (like lists, dictionaries, or custom objects) into a byte stream. |
| 10 | + - Deserialization (Unpickling): Converts the byte stream back into the original Python object. |
| 11 | + |
| 12 | + |
| 13 | +Some of the `pickle` module functions : |
| 14 | + |
| 15 | +- `pickle.dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None)` : Serializes `obj` and writes it to the open file object `file`. |
| 16 | +- `pickle.dumps(obj, protocol=None, *, fix_imports=True, buffer_callback=None)` : Serializes `obj` to a byte stream and returns it. |
| 17 | +- `pickle.loads(bytes_object, *, fix_imports=True, encoding="ASCII", errors="strict", buffers=None)` : Deserializes `bytes_object` (a byte stream) to a Python object. |
| 18 | + |
| 19 | + |
| 20 | +#### Serializing and writing to file |
| 21 | +```python |
| 22 | +import pickle |
| 23 | + |
| 24 | + |
| 25 | +data = {'key': 'value', 'number': 42} |
| 26 | +with open('data.pkl', 'wb') as file: |
| 27 | + pickle.dump(data, file) |
| 28 | +``` |
| 29 | + |
| 30 | +#### Reading and Deserializing from a File |
| 31 | +```python |
| 32 | +import pickle |
| 33 | + |
| 34 | +with open('data.pkl', 'rb') as file: |
| 35 | + loaded_data = pickle.load(file) |
| 36 | +print(loaded_data) |
| 37 | +``` |
0 commit comments