Data File Handling in Python W.S (C.S)
Data File Handling in Python W.S (C.S)
5. What is the difference between the following set of statements (a) and (b):
a) P = open(“practice.txt”,”r”)
P.read(10)
b) with open(“practice.txt”, “r”) as P:
x = P.read()
Answer – File P will read 10 characters in part “a” but won’t print anything; in part “b,”
however, it will read every character in the practise file and save it in the variable “x.”
6. Write a command(s) to write the following lines to the text file named hello.txt.
Assume that the file is opened in append mode.
“ Welcome my class”
“It is a fun place”
“You will learn and play”
Answer –
f = open(“hello.txt”,”a”)
f.write(“Welcome my class”)
f.write(“It is a fun place”)
f.write(“You will learn and play”)
f.close()
7. Write a Python program to open the file hello.txt used in question no 6 in read mode
to display its contents. What will be the difference if the file was opened in write mode
instead of append mode?
Answer –
f = open(“hello.txt”,”r”)
x = f.read()
print(x)
8. Write a program to accept string/sentences from the user till the user enters “END”
to. Save the data in a text file and then display only those sentences which begin with an
uppercase alphabet.
Answer –
f = open(“example.txt”,”w”)
while True :
sen = input(“Enter something ( Enter END for quit ) :-“)
if sen == “END” :
break
else :
f.write(sen + “\n”)
f.close()
print()
print(“Lines started with Capital letters :-“)
f = open(“example.txt”,”r”)
print()
data = f.readlines()
for i in data :
if i[0].isupper() :
print(i)
f.close()
9. Define pickling in Python. Explain serialization and deserialization of Python object.
Answer – Pickling is a process also called serialization where an object is converted into stream of
bytes.
Serialization is the process of transforming data or an object in memory (RAM) to a stream of bytes
called byte streams. These byte streams in a binary file can then be stored in a disk or in a database or
sent through a network.
De-serialization or unpickling is the inverse of pickling process where a byte stream is converted back
to Python object.
Answer –
import pickle
file = open(“Pathwalla.dat”,”wb”)
while True :
dic = { }
Item_No = int(input(“Enter Item no.”))
Item_Name = input(“Enter Item name :-“)
Qty = int(input(“Enter Quantity :- “))
Price = float(input(“Enter price :-“))
file.close()
print()
file = open(“Pathwalla.dat”,”rb”)
try :
while True :
dic = pickle.load(file)
print( “Item No. :”,”\t”, dic[ “Item_No” ] )
print( “Item Name :”,”\t”, dic[ “Item_Name” ] )
print( “Quantity :”,”\t”, dic[ “Qty” ] )
print( “Price of one :”,”\t”,dic[ “Price” ] )
print( “Amount :”, “\t” , dic[ “Qty” ] * dic[ “Price” ] )
print()
except :
file.close()