SBOA School Senior Secondary, Madurai – 19
Class : 12 Computer Science
Revision Notes on File Handling
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 [Link] for reading, open function will be written as f =
_______.
7. To open file [Link] for writing, open function will be written as f =
________.
8. In f=open(“[Link]”,”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 9. close
2. File Handling 10. read(15)
3. I/O Operations 11. readline()
4. Data file 12. readlines()
5. Text File 13. write()
6. open(“[Link]”,”r”) 14. writelines()
7. open(“[Link]”,”w”) 15. append
8. File handle or File Object 16. flush()
17. ASCII, UNICODE 19. open()
18. CSV 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(“[Link]”, “r”), r refers to __________.
a. File handle b. File object c. File Mode 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 = [Link]();print(dt[3])b. dt=[Link](4) ;print(dt[3])
c. dt=[Link](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/ Conceptual Questions
1. What do you mean by file? What do you mean by file
handling?
The file refers to the collection of bytes stored in computer
storage.
Data can be stored in various forms in a file.
These files saved in a specific format with a specific extension.
Every file needs to have a specific program to read them.
Fille handling refers to the process of handling data using
software for IO operations.
2. Explain open() function with its syntax in detail.
The open function has the following syntax:
Open a text file: Syntax:<file object> =
open(file_name,access_mode)
file object : It is just like a variable or object
open(): It is a function with two parameters.
file_name: It accepts a file name with .txt extension.
access_mode: It specifies the mode to access the file. The
default mode is reading mode.
These modes are
r: to read a file
w: to write
a: append contents
3. Does python create itself if the file doesn’t exist in the
memory? Illustrate your answer with an example.
Python will create a file automatically when the open function is
used with write mode.
Example:
f=open(“[Link]”,”w”)
[Link](“Hello\nHow are you?”)
[Link]()
4. Write a statement to create a [Link] file with the following
text.
1. Python file handling is very interesting and useful.
2. This is a text file created through python.
f=open(“[Link]”,”w”)
[Link](“Python file handling is very interesting and useful.”)
[Link](“This is a text file created through python.”)
[Link]()
5. List out the basic file modes available in python.
r – to read from the file
w – to write into the file
a – append data into the file already exists
r+/w+ – to perform read and write together
rb/wb/ab – read, write and append data into binary files
6. Compare text files, binary files and csv files and write pros
and cons of each of them.
7. Text Files Binary Files CSV Files
1
It is capable to It is capable to handle It is very common
handle textual format and platform
data. large file. independent.
It consists of series
of lines of a set of It consists of data with It consists of plain text
letters, numbers or a specific pattern with a list of data with a
2 symbols (String) without any delimiter. delimiter.
No specific programs It can be read using text
Any text editors like can be used to read editors like notepads
notepad can be them, python provides and spreadsheet
3 used to read them. functions to read data. software.
It terminates a line
automatically when the
Every line ends There is no specific EOL delimiter is not used
4 with EOL. character. after data.
Application-Based questions
The following section contains few case study based questions for Data
file handling in python class 12.
1. Write a python program to create and read the [Link] file in
one go and print the contents on the output screen.
Answer:
# Creating file with open() function
f=open("[Link]","w")
[Link]("My city is very clean city.")
[Link]()
# Reading contents from [Link] file
f=open("[Link]","r")
dt = [Link]()
print(dt)
[Link]()
2. Consider following lines for the file [Link] 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("[Link]")
l = [Link]()
l2 = [Link](18)
ch3=[Link](10)
print(l2)
print(ch3)
print([Link]())
[Link]()
Output:
Friends are honest
, Friends
are best !
Explanation:
In line no. 2, [Link]() 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 [Link](18) which reads next
18 characters and place the cursor at the next position i.e. comma (,) , in
next statement [Link](10) reads next 10 characters and stores in ch3
variable and then cursor moves to the next position and at last [Link]()
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 – [Link].
def count_lines():
f = open("[Link]")
cnt =0
for lines in f:
cnt+=1
print("no. of lines:",cnt)
[Link]()
4. Write a function display_oddLines() to display odd number lines
from the text file. Consider above file – [Link].
def display_oddLines():
f = open("[Link]")
cnt =0
for lines in f:
cnt+=1
if cnt%2!=0:
print(lines)
[Link]()
5. Write a function cust_data() to ask user to enter their names
and age to store data in [Link] file.
def cust_data():
name = input("Enter customer name:")
age=int(input("Enter customer age:"))
data = str([name,age])
f = open("[Link]","w")
[Link](data)
[Link]()
Revision Notes on Python Library
Theory Questions
1. What is a library?
2. Write a few examples of commonly used libraries with examples.
3. What is the python module? Explain the structure of the python
module.
4. How to import the python module?
5. Explain the commonly used python mathematical methods/functions
with examples.
6. Explain the commonly used python string/text methods/functions with
examples.
7. What do you mean by Library Function in Python?
8. Enlist some commonly used libraries of python and explain in short.
9. Explain the structure of python module.
10. Explain some commonly used mathematical functions in detail with
example.
11. Explain some commonly used string functions in detail with example.
12. How to import a python module? or What are the ways to
insert python modules in a program?
Ans.: To insert a python module you can use the import statement in the
following two ways:
1. import command: Ex. import math
2. from import: Ex. from math import *
13. Write related library function name to do the following:
1. Display the negative number into positive: abs()
2. Display nearest integer for the given number: ceil()
3. Get the remainder: fmod(), remainder()
4. Get the compute cube of a given number: pow()
5. Get the square root of the given number: sqrt()
6. Convert the first letter of the text into capital: capitalise()
7. Join two words: join()
8. Convert the text into the lower case: lower()
14. Name the module required to import for the following
functions:
1. pow() – math
2. fabs() – math
Application Based questions
Error Based questions
1. def python_lib():
x = float(input(“Enter the number:”))
y = [Link]((x)
Assume that, x = 10.66777878
Ans.: There are three errors in the code, import math statement is
missing and y = [Link](x) should be used.
2. x = 5
y = [Link](3)
Ans.: There are two errors in the code, import math statement is missing
and pow() function required two parameters,
3. a = 10
b = sqrt(a,2)
Assume that math module is imported.
Ans.: sqrt() function requires only one parameter.
4. s = “Welcome to My Blog”
print([Link]())
Ans.: Error in print() function. The method capitalize() not written
correctly and str word is not required.
Output Questions
Note: Assume that the math module is imported wherever required.
1. x = -45.2342343254325
b = [Link](x)
y = [Link](b)
print(y+5)
Ans.: 51
fabs() function convert the nagetive value into postive. As ceil() function
returns the nearest integer of the passed argument value as well as in
print() function y+5 is written. So [Link](x) returns 46, 46 + 5 =
51.
2. import math
def python_lib():
s = “Computer Science with Python”
print([Link]())
print([Link]())
print([Link]())
print([Link](‘with’,’-‘))
python_lib()
Ans.:
cOMPUTER sCIENCE WITH pYTHON
Computer Science With Python
[‘Computer’, ‘Science’, ‘with’, ‘Python’]
Computer Science – Python
3. import math
def python_lib():
s = “Python is midlle level language. Learning python is
fun.”
c = 0
w = [Link]()
for i in w:
if i==’is’:
c = c + 1
print(c)
python_lib()
Ans.: 2
In this code w = [Link]() is used that generates a list of words from the
text. Then in the for loop, if condition is given for counting the word ‘is’ is
available 2 times in the text. Then finally the counter variable is printed.
So the output is 2.
4. import math
def python_lib():
s = “Python is Programing Platform that Playful”
w = [Link]()
c=0
for i in w:
if i[0]==’P’:
print(i,end=”#”)
python_lib()
Ans.: Python#Programing#Platform#Playful#
In for loop, i[0] is searching the word starts with letter P and printed in the
next line.
5. import math
def python_lib():
s = “Python is Programing Platform that is Playful”
s1=”
print([Link](‘yPt’))
print([Link](‘Pul’))
print([Link]([s,’ in 2020′]))
python_lib()
Ans.:
hon is Programing Platform that is Playful
Python is Programing Platform that is Playf
Python is Programing Platform that is Playful in 2020
Find the output for the following:
1.
def str_exp():
str1= 'COVID-19,Sanitizer,Mask,LockDown'
str1=[Link]()
str2 =[Link](',')
for i in str2:
if i<'s':
print([Link](i))
else:
print([Link](i))
str_exp()
Answer:
covid-19
SANITIZER
mask
lockdown
In the above example, the text starts with the alphabet ‘s’ and letter
coming after ‘s’ will be converted into uppercase and rest text will be in
lower case.
2.
def str_exp():
str1='Covid - 19 forces the entire worl to be lockdown'
str1=[Link]('e','i')
print(str1)
str_exp()
Answer:
Covid – 19 forcis thi intiri worl to bi lockdown
All e replace with the letter i in the text.
3.
def str_exp():
str="Lockdown to Unlock 1.0"
d=[Link]()
print(d)
str_exp()
Answer:
[‘Lockdown’, ‘to’, ‘Unlock’, ‘1.0’]
The words will be separated in a string after space
4.
import math
def mth_exp():
a=5.5
b=3.75
c=2.25
print(round([Link]([a,b,c]),0))
mth_exp()
Answer:
12.0
Function fsum() returns sum of specified variables a,b,c. The values are
5.5 + 3.75 + 2.25 = 11.5. Then round function returns next integer if the
adjecent digit is more than 5. So the final output will be 12.0
Programs
1. Write a program to accept the marks of 5 subjects and do the following:
1. Display the total using fsum() function
2. Display total marks in round integers
Ans.:
import math
def compute_result():
eng=float(input("Enter marks of English:"))
phy=float(input("Enter marks of Physics:"))
che=float(input("Enter marks of Chemistry:"))
mat=float(input("Enter marks of Maths:"))
cs=float(input("Enter marks of Computer Science:"))
tot=round([Link]([eng,phy,che,mat,cs]),0)
print("Total:",tot)
compute_result()
2. Write a program to display the computation of power using math module function.
Ans.:
import math
def compute_power():
no=int(input("Enter the number:"))
p=int(input("Enter the power to be raised:"))
ans=[Link](no,p)
print("The",p,"power of ",no," is:", ans)
compute_power()
3. Write a program to convert the first letter of the sentence into a capital letter.
Ans.:
def first_upper():
s=input("Enter the sentences:(in lower case:)")
print([Link]())
first_upper()
4. Write a program to convert the first letter of each word of the sentence into a capital
letter.
def first_upper():
s=input("Enter the sentences:(in lower case:)")
print([Link]())
first_upper()