Monday, April 3, 2023

Serialization in Python

 There are different ways in Python to read data from files and to write data to files.


1. Using input from console

x = input('Enter your name:')

print('Hello, ' + x)



2. Using File Handling methods

The file handling methods in Python include open, close, readlines and writelines.

Common operation modes for files are r(read), w(write), a(append at end) and r+(read and write).


# read

text_file = open('/Users/pankaj/abc.txt','r')

line_list = text_file.readlines()

for line in line_list:

    print(line)

text_file.close()


# write

text_file = open('/Users/pankaj/file.txt','w')

word_list= []

for i in range (1, 5):

    print("Please enter data: ")

    line = input() 

    word_list.append(line) 

text_file.writelines(word_list) # overwrites file data

text_file.close() 


# append

text_file = open('/Users/pankaj/file.txt','a')

word_list= []

for i in range (1, 5):

    print("Please enter data: ")

    line = input() 

    word_list.append(line)

text_file.writelines(word_list)

text_file.close() 


The file.seek(7) moves the cursor to the specified location.



3. Serialization

Serialization is the process of converting the object into a format that can be stored or transmitted.  Python has a number of built-in modules for this process: marshall, json, and pickle. The marshall is mainly used by the interpreter. The json produces human-readable output and works well with other languages, but it works only with certain data types.So pickle provides the best Serialization solution. 

pickle.dump(): to convert data into serialized form

pickle.load(): to convert serialized format into original data type.


# pickle

import pickle

number_of_data = int(input('Enter the number of data : '))

data = []

for i in range(number_of_data):

    raw = input('Enter data '+str(i)+' : ')

    data.append(raw)

file = open('important', 'wb')

pickle.dump(data, file)

file.close()


# unpickle

file = open('important', 'rb')

data = pickle.load(file)

file.close()

for item in data:

    print(item)

No comments: