Computer Science
What will be the output of the following code ?
import pickle
ID = {1:"Ziva", 2:"53050", 3:"IT", 4:"38", 5:"Dunzo"}
fin = open("Emp.pkl","wb")
pickle.dump(ID, fin)
fin.close()
fout = open("Emp.pkl",'rb')
ID = pickle.load(fout)
print(ID[5])
Python
Python File Handling
1 Like
Answer
Dunzo
Working
import pickle
— Imports thepickle
module, which is used for serializing and deserializing Python objects.ID = {1: "Ziva", 2: "53050", 3: "IT", 4: "38", 5: "Dunzo"}
— Defines a dictionary namedID
with keys and values.fin = open("Emp.pkl", "wb")
— Opens a file namedEmp.pkl
in binary write mode ("wb").pickle.dump(ID, fin)
— Serializes theID
dictionary and writes it to the file handlefin
using thepickle.dump()
function.fin.close()
— Closes the filefin
after writing the pickled data.fout = open("Emp.pkl", 'rb')
— Opens the fileEmp.pkl
again, this time in binary read mode ("rb"), to read the pickled data.ID = pickle.load(fout)
— Deserializes the data from the filefout
using thepickle.load()
function and assigns it to the variableID
. This effectively restores the original dictionary from the pickled data.print(ID[5])
— Prints the value associated with key 5 in the restoredID
dictionary, which is "Dunzo".
Answered By
3 Likes
Related Questions
Write a method in Python to read the content from a text file diary.txt line by line and display the same on screen.
Write a method in Python to write multiple line of text contents into a text file mylife.txt.line.
What will be the output of the following code ?
import pickle List1 = ['Roza', {'a': 23, 'b': True}, (1, 2, 3), [['dogs', 'cats'], None]] List2 = ['Rita', {'x': 45, 'y': False}, (9, 5, 3), [['insects', 'bees'], None]] with open('data.pkl', 'wb') as f: f.write(List1) with open('data.pkl', 'wb') as f: f.write(List2) with open('data.pkl', 'rb') as f: List1 = pickle.load(f) print(List1)
What is the output of the following considering the file data.csv given below.
File data.csv contains: Identifier;First name;Last name 901242;Riya;Verma 207074;Laura;Grey 408129;Ali;Baig 934600;Manit;Kaur 507916;Jiva;Jain
import csv with open('C:\data.csv', 'r+') as f: data = csv.reader(f) for row in data: if 'the' in row : print(row)