Answer to Question #280944 in Python for Annette

Question #280944

Write a program which creates a class named babyRecord with four methods.

a) One method will be used to write details of a child including date of birth, name, parent names and hospital name into a file called baby_data.txt.

b) The second method will be used to read from the file baby_data.txt and store the data in a dictionary called records.

c) The third method will be used to search for a baby using baby name or parent names information in the file called baby_data.txt.

d) The last method will be used to delete records in the dictionary and file respectively.

e) Clearly show how exceptions are handled in your program in each method.


1
Expert's answer
2021-12-20T10:03:34-0500
# importing the module
import json


# reading the data from the file
with ​​open('dictionary.txt') as f:
	data = f.read()


print("Data type before reconstruction : ", type(data))
	
# reconstructing the data as a dictionary
js = json.loads(data)


print("Data type after reconstruction : ", type(js))
print(js)

#c)
# importing the module
import ​​pickle


# opening file in write mode (binary)
file ​= open("dictionary.txt", "wb")


my_dict = {"Name": "John",
		"Age": 21,
		"Id": 28}


# serializing dictionary
pickle.dump(my_dict, file)


# closing the file
file.close()


# reading the data from the file
with ​​open('dictionary.txt', 'rb') as handle:
	data = handle.read()


print("Data type before reconstruction : ", type(data))


# reconstructing the data as dictionary
d = pickle.loads(data)


print("Data type after reconstruction : ", type(d))

#d)
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)


# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)


# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)

#Clearly show how exceptions are handled in your program in each method.
try:    
    a = int(input("Enter a:"))    
    b = int(input("Enter b:"))    
    c = a/b  
    print("a/b = %d"%c)    
# Using Exception with except statement. If we print(Exception) it will return exception class  
except Exception:    
    print("can't divide by zero")    
    print(Exception)  
else:    
    print("Hi I am else block"

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS