You are on page 1of 23

DAYANAND ANGLO VEDIC PUBLIC SCHOOL, AIROLI

SUB : COMPUTER SCIENCE


Std : XII
Practice Programs Worksheet

Topic : File Handling


Text File Programs :

1. To open a file c:\res.txt for reading, we can use (select all correct
options):
a. file = open("c: \res.txt", "r")
b. file = open("c:\ \res.txt", "r")
c. file = open(r"c: \res.txt", "r")
d. file = open(file = "c:\res.txt", "r")
e. file = open(file = "c:\ \res.txt", "r")
f. file = open("c:\ \res.txt")

a) d, e, f b) a, e, f
C) b, d, f d) b, c, f

2. #Program to read data from data file in read mode and


#count the particular word occurrences in given string.

f=open("test.txt",'r')
read=f.readlines()

chk=input("Enter String to search : ")


count=0
for sentence in read:
word=sentence.split()
for each in word:
if chk == each:
count+=1
print("The search String ", chk, "is present : ", count, "times")

f.close()

3. #Program to write dictionary to a binary file

import pickle
dict1 = {'Python': 90, 'Java': 95, 'C++': 85}
f = open('bin_file.dat','wb')
pickle.dump(dict1,f)
f.close()
4. #Program to read data from data file in read mode and
#write the words starting with letter ‘T’
#in another file in python

f=open("test.txt",'r')
read=f.readlines()
f1=open("new.txt",'w')
for ln in read:
if ln.startswith("T"):
f1.write(ln)

f.close()
f1.close()

5.

Ans :

6.

Create file phonebook.txt that stores the details in following format: Name
Phone
Jivin 86666000
Kriti 1010101

Obtain the details from the user.

Ans :
fp1 = open("phonebook.txt", 'w')
fp1.write ("Name")
fp1.write (" ")
fp1.write ("Phone")
fp1.write ("\n")
while True:
name = input ("Enter name:")
phno = input ("Enter phone no:")
fp1.write (name)
fp1.write (" ")
fp1.write ("phno")
fp1.write ("\n")
ch = input("Want to enter more=y/n")
if ch == 'N’ OR ch == 'n’:
break
fp1.close()

7. A text file "Quotes.Txt" has the following data written in it : Living a


life you can be proud of Doing you Spending your time with people and
activities that are important to you Standing up for things that are right
even when it's hard Becoming the best version of you i.

Write a user-defined function to display the total number of words present in


the file.
8. Write a function CountYouMe() in Python which reads the contents
of a text file Notes.txt and counts the words You and Me (not case
sensitive).

9.

Binary Files

Program 1 Pickling data in Python

import pickle
listvalues=[1,"Geetika",'F', 26]
fileobject=open("mybinary.dat", "wb")
pickle.dump(listvalues,fileobject)
fileobject.close()

Program 2 Unpickling data in Python

import pickle
print("The data that were stored in file are: ")
fileobject=open("mybinary.dat","rb")
objectvar=pickle.load(fileobject)
fileobject.close()
print(objectvar)
Output of Program 2
>>> RESTART: Path_to_file\Program2.py
The data that were stored in file are: [1, 'Geetika', 'F', 26]

Program 3: To perform basic operations on a binary file using pickle module

# Program to write and read employee records in a binary file

import pickle
print("WORKING WITH BINARY FILES")
bfile=open("empfile.dat","ab")
recno=1
print ("Enter Records of Employees")
print(“taking data from user and dumping in the file as list object”)
while True:
print("RECORD No.", recno)
eno=int(input("\tEmployee number : "))
ename=input("\tEmployee Name : ")
ebasic=int(input("\tBasic Salary : "))
allow=int(input("\tAllowances : "))
totsal=ebasic+allow
print("\tTOTAL SALARY : ", totsal)
edata=[eno,ename,ebasic,allow,totsal]
pickle.dump(edata,bfile)
ans=input("Do you wish to enter more records (y/n)? ")
recno=recno+1
if ans.lower()=='n':
print("Record entry OVER ")
print()
Break

# retrieving the size of file


print("Size of binary file (in bytes):",bfile.tell())
bfile.close()

# Reading the employee records from the file using load() module
print("Now reading the employee records from the file")
print()
readrec=1
try:
#with open("empfile.dat","rb") as bfile:

bfile=open("empfile.dat","rb")
while True:
edata=pickle.load(bfile)
print("Record Number : ",readrec)
print(edata)
readrec=readrec+1
except EOFError:
pass
bfile.close()

Output of Program 3:
>>>
RESTART: Path_to_file\Program3.py
WORKING WITH BINARY FILES
Enter Records of Employees
RECORD No. 1
Employee number : 11
Employee Name : D N Ravi
Basic Salary : 32600
Allowances : 4400
TOTAL SALARY : 37000
Do you wish to enter more records (y/n)? y
RECORD No. 2
Employee number : 12
Employee Name : Farida Ahmed
Basic Salary : 38250
Allowances : 5300
TOTAL SALARY : 43550
Do you wish to enter more records (y/n)? n
Record entry OVER
Size of binary file (in bytes): 216
Now reading the employee records from the file
Record Number : 1
[11, 'D N Ravi', 32600, 4400, 37000]
Record Number : 2
[12, 'Farida Ahmed', 38250, 5300, 43550]

Program no. 4

Ans :
Program No. 5

Ans :
Short Answer Questions – binary files in python

[1] Write steps to append data into binary files.


[2] Mention steps to search a record from binary files.
[3] Elaborate steps to update records in binary file.
[4] Write steps to delete records from binary file.
[5] Compare how binary files are better than text files?
[6] Explain various file modes can be used with binary file operations.
[7] What is pickle module? How to import pickle module in python program?
[8] How to use dump() and load() functions?

Case study Based questions


[1] Ms. Sejal is working on the sports.dat file but she is confused about how
to read data from the binary file. Suggest a suitable line for her to fulfill her
wish.
import pickle

def sports_read():

f1 = open("sports.dat","rb")

_________________

print(data)

f1.close()

sports_read()

–> data = pickle.load(f1)


[3] Improve above code and write the correct code to display all records from
the file.
f1 = open("sports.dat","rb")

try:

while True:

dt = pickle.load(f1)

print(dt)

except Exception:

f1.close()

[2] Develop python code to insert records in g_meet.dat binary file until user
press ‘n’. The information is Google meeting id, google meeting time, and
class.
f1 = open("g_meet.dat","ab")

while True:

gmeet_id=input("Enter id:")

gmeet_time=input("Enter time:")

gmeet_class =int(input("Enter google meet class:"))

rec={"Google Meeting id":gmeet_id,"Gogole Meet


Time":gmeet_time,"Google Meet Class":gmeet_class}

pickle.dump(rec,f1)

ch = input("Want more records:")

ch=ch.lower()

if ch=='n':

break

f1.close()

[3] Write a function to update record from g_meet.dat file.


[4] Create a function to delete a record from g_meet.dat file.
VSA Type questions (1M)

Fill in the blanks

1. A collection of bytes stored in computer’s secondary memory is known


as _______.
2. ___________ is a process of storing data into files and allows to
performs various tasks such as read, write, append, search and modify in
files.
3. The transfer of data from program to memory (RAM) to permanent
storage device (hard disk) and vice versa are known as __________.
4. A _______ is a file that stores data in a specific format on secondary
storage devices.
5. In ___________ files each line terminates with EOL or ‘\n’ or carriage
return, or ‘\r\n’.
6. To open file data.txt for reading, open function will be written as f =
_______.
7. To open file data.txt for writing, open function will be written as f =
________.
8. In f=open(“data.txt”,”w”), f refers to ________.
9. To close file in a program _______ function is used.
10. A __________ function reads first 15 characters of file.
11. A _________ function reads most n bytes and returns the read bytes in
the form of a string.
12. A _________ function reads all lines from the file.
13. A _______ function requires a string (File_Path) as parameter to write in
the file.
14. A _____ function requires a sequence of lines, lists, tuples etc. to write
data into file.
15. To add data into an existing file ________ mode is used.
16. A _________ function is used to write contents of buffer onto storage.
17. A text file stores data in _________ or _________ form.
18. A ___________ is plain text file which contains list of data in tabular
form.
19. You can create a file using _________ function in python.
20. A __________ symbol is used to perform reading as well as writing on
files in python.
Answers:

1. File
2. File Handling
3. I/O Operations
4. Data file
5. Text File
6. open(“data.txt”,”r”)
7. open(“data.txt”,”w”)
8. File handle or File Object
9. close
10. read(15)
11. readline()
12. readlines()
13. write()
14. writelines()
15. append
16. flush()
17. ASCII, UNICODE
18. CSV
19. open()
20. +

MCQs

1 Every file has its own identity associated with it. Which is known as –
a. icon
b. extension
c. format
d. file type

2 Which of the following is not a known file type?


a. .pdf
b. jpg
c. mp3
d. txp

3. In f=open(“data.txt”, “r”), r refers to __________.


a. File handle
b. File object
c. File Mode
d Buffer

4. EOL stands for


a. End Of Line
b. End Of List
c. End of Lines
d. End Of Location

5. Which of the following file types allows to store large data files in the
computer memory?
a. Text Files
b. Binary Files
c. CSV Files
d. None of these

6. Which of the following file types can be opened with notepad as well as ms
excel?
a. Text Files
b. Binary Files
c. CSV Files
d. None of these

7. Which of the following is nor a proper file access mode?


a. close
b. read
c. write
d. append

8. To read 4th line from text file, which of the following statement is true?
a. dt = f.readlines();print(dt[3])
b. dt=f.read(4) ;print(dt[3])
c. dt=f.readline(4);print(dt[3])
d. All of these

9 Which of the following function flushes the files implicitly?


a. flush()
b. close()
c. open()
d. fflush()

10. Which of the following functions flushes the data before closing the file?
a. flush()
b. close()
c. open()
d. fflush()

Short answer questions (SA)/ Conceptual Questions


(2M)
Please refer notes section for the answers on Data file handling in python
class 12.
1 What do you mean file? What do you mean by file handling?
2 Explain open() function with its syntax in detail.
3 Does python create a itself if the file doesn’t exist in the memory? Illustrate
your answer with example.
Answer: Python will creates a file automatically when open function is used
with write mode.
Example:
f=open("data.txt","w")

f.write("Hello\nHow are you?")

f.close()

4 Write a statement to create data.txt file with following text.


Python file handling is very interesting and useful.
This is a text file created through python.
5 List out the basic file modes available in python.
6 Compare text files, binary files and csv files and write pros and cons of each
of them.
Application Based questions
1. Write a python programs to create and read city.txt file in one go and print
the contents in the output screen.
Answer:
# Creating file with open() function

f=open("city.txt","w")

f.write("My city is very clean city.")

f.close()

# Reading contents from city.txt file

f=open("city.txt","r")

dt = f.read()

print(dt)

f.close()

2 Consider following lines for the file friends.txt and predict the output:
Friends are crazy, Friends are naughty !

Friends are honest, Friends are best !

Friends are like keygen, friends are like license key !

We are nothing without friends, Life is not possible without friends !

f = open("friends.txt")

l = f.readline()

l2 = f.readline(18)

ch3=f.read(10)

print(l2)

print(ch3)

print(f.readline())

f.close()

Output:
Friends are honest
, Friends
are best !
Explanation:
In line no. 2, f.readline() function reads first line and stores the output string
in l but not printed in the code, then it moves the pointer to next line in the
file. In next statement we have f.readline(18) which reads next 18 characters
and place the cursor at the next position i.e. comma (,) , in next statement
f.read(10) reads next 10 characters and stores in ch3 variable and then cursor
moves to the next position and at last f.readline() function print() the entire
line.

3 Write a function count_lines() to count and display the total number of lines
from the file. Consider above file – friends.txt.
def count_lines():

f = open("friends.txt")

cnt =0

for lines in f:

cnt+=1

print("no. of lines:",cnt)

f.close()

4 Write a function display_oddLines() to display odd number lines from the


text file. Consider above file – friends.txt.
def display_oddLines():

f = open("friends.txt")

cnt =0

for lines in f:

cnt+=1

if cnt%2!=0:

print(lines)

f.close()
5 Write a function cust_data() to ask user to enter their names and age to store
data in customer.txt file.
def cust_data():

name = input("Enter customer name:")

age=int(input("Enter customer age:"))

data = str([name,age])

f = open("customer.txt","w")

f.write(data)

f.close()

CSV Files

 What is a CSV ?
* CSV (Comma Separated Values) is a simple file format used to
store tabular data, such as a spreadsheet or database.

* A CSV file stores tabular data (numbers and text) in plain text.

* Each line of the file is a data record.

* Each record consists of one or more fields, separated by


commas.

* The use of the comma as a field separator is the source of the


name for this file format.

* CSV files allows to choose a different delimiter character such


as ‘\t’,  ‘:’ , ‘;’ , ‘|’. but the default delimiter is ‘,’comma.
* To read and write in CSV files we need to import csv module.

* csv module provides two specific objects -reader and writer


to read and write into the file.

* These objects read and write delimited sequence as records in a


csv file.

SA questions (2M)

Example 1: Read CSV Having Comma Delimiter

import csv

file=open('people.csv', 'r')

with open('people.csv', 'r') as file:

reader = csv.reader(file)

for row in reader:

print(row)

Output

['Name', 'Age', 'Profession']

['Jack', '23', 'Doctor']

['Miller', '22', 'Engineer']

Example 2: Read CSV file Having Tab Delimiter

import csv
with open('people.csv', 'r',) as file:

reader = csv.reader(file, delimiter = '\t')

for row in reader:

print(row)

Example 3: Write to a CSV file

import csv

with open('protagonist.csv', 'w', newline='') as file:

writer = csv.writer(file)

writer.writerow(["SN", "Movie", "Protagonist"])

writer.writerow([1, "Lord of the Rings", "Frodo Baggins"])

writer.writerow([2, "Harry Potter", "Harry Potter"])

Example 4: Writing multiple rows with writerows()

If we need to write the contents of the 2-dimensional list to a CSV file, here's how
we can do it.

import csv

csv_rowlist = [["SN", "Movie", "Protagonist"], [1, "Lord of the Rings", "Frodo


Baggins"], [2, "Harry Potter", "Harry Potter"]]

with open('protagonist.csv', 'w') as file:

writer = csv.writer(file)

writer.writerows(csv_rowlist)

CSV File questions (3M)

1. Write data into CSV file :


import csv
f=open("emp.csv", "w", newline='')
w=csv.writer(f)
w.writerow(["EMP NO","EMP NAME","EMP SAL","EMP ADDR"])
n=int(input("Enter Number of Employees:"))
for i in range(n):
eno=input("Enter Employee No:")
ename=input("Enter Employee Name:")
esal=input("Enter Employee Salary:")
eaddr=input("Enter Employee Address:")
w.writerow([eno, ename, esal, eaddr])
print("Total Employees data written to csv file successfully")

Python program to create a CSV file named “student.csv”,


to store Roll,Name and Per of students.
Sol:

#writing records in csv file


import csv
fh=open('student.csv','w',newline='')
stuwriter=csv.writer(fh)
stuwriter.writerow(['Rollno','Name','Marks']) # write header row
sturec= [ ['101', 'Nikhil', '99'],
['102', 'Sanchit', '98'],
['103', 'Aditya', '98'],
['104', 'Sagar', '87'],
['105', 'Prateek', '88'],
]
for i in sturec:
stuwriter.writerow(i)
fh.close()
Text file questions (2M)

#Program in python to type text in a file till ~ is pressed as


rightmost character

f=open("d:\\a.txt","w")
s=''
print("Type text for file,press ~ as rightmost character for
exit/save contents")
while s!='~':
s=input()
f.write(s+"\n")
s=s[-1:]
f.close()
print("file contents saved")

#Program in python to read entire text file


f=open("d:\\a.txt","r")
s=f.read()
print(s)
f.close()

#Program in python to append text at the end of text file

f=open("d:\\a.txt","a")
s=input("enter a string to add at the end of file")
f.write(s)
f.close()

#Program in python to read line by line from text file


f=open("d:\\a.txt","r")
for t in f.readlines():
print(t,end="")
f.close()

#Program in python to read entire file line by line in a list


f=open("d:\\a.txt","r")
t=f.readlines()
print(t)
f.close()

#Program in python to read each word separately


f=open("d:\\a.txt","r")
for t in f.readlines():
for r in t.split():
print(r)
f.close()

#Program in python to count no. of words in a text file


f=open("d:\\a.txt","r")
c=0
for t in f.readlines():
for r in t.split():
c=c+1
print("no of words in file are ",c)
f.close()

#Program in python to show word with maximum length from


a text file
f=open("d:\\a.txt","r")
lword=''
for t in f.readlines():
for r in t.split():
if len(r)>len(lword):
lword=r
print("maximum length word is ",lword)
f.close()

#Python program to combine each line from first file with the
corresponding line in second file

f=open("d:\\a.txt","r")
g=open("d:\\b.txt","r")
for line1, line2 in zip(f,g):
print(line1+line2)

#Python Program to Copy the Contents of One File into Another

f=open("d:\\a.txt","r")
g=open("d:\\c.txt","w")
for line in f:
g.write(line)
f.close()
g.close()
print("file contents copied")
#Python Program to Search for a word in text file and print
part of line
f=open("d:\\c.txt","r")
for line in f.readlines():
for part in line.split():
if "volatile" in part:
print(line)
f.close()
Note :- in above program we are searching word “volatile”

#Python Program to convert file contents upper to lower and


lower to upper case in the same opened file.

You might also like