[go: up one dir, main page]

0% found this document useful (0 votes)
55 views15 pages

CS - File Handling

The document discusses file handling in Python. It defines what a file is and the need for file handling. It describes different types of files and file operations like opening, reading, writing and closing files. It also discusses text file handling and provides examples of reading from and writing to text files.

Uploaded by

masterbro915
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views15 pages

CS - File Handling

The document discusses file handling in Python. It defines what a file is and the need for file handling. It describes different types of files and file operations like opening, reading, writing and closing files. It also discusses text file handling and provides examples of reading from and writing to text files.

Uploaded by

masterbro915
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

MODERN OXFORD PUBLIC SCHOOL, BAM [CS MATERIAL]

FILE HANDLING
What is File?

A file is a sequence of bytes on the disk where a group of related data is stored. It is a named location on a
backup storage media where data are permanently stored.

Need of Handling File in Python

In an interactive program, when user inputs data, it is stored in the main memory (RAM) which is volatile
(data would be lost when the power supply is off). The main objective of handling file is to store data
permanently in a backup device so that it can be accessed latter.

File handling in Python enables us to create, update, read, and delete the files stored on the disk through
program.

Types of File

 Text file: data are stored in a platform-dependent encoding format (ASCII or Unicode, UTF8 etc).
This mode is about conversion of line endings.
 Binary file: data are stored in the same format as in memory (raw). No translation or encoding
applied while rendering data.
 CSV file: (Comma Separated Values file) is a type of plain text file that uses specific structuring to
arrange tabular data.
Text file Binary file CSV file
It is capable to handle textual It is capable to handle binary It is very common format and
data. data in the same format as in platform independent.
memory.
It consists of series of lines of a It consists of data with a It consists of plain text with a
set of letters, numbers or specific pattern without any list of data with a delimiter.
symbols (String) delimiter.
Any text editors like notepad can No specific programs can be It can be read using text editors
be used to read them. used to read them, python like notepads and spreadsheet
provides functions to read data. software.
Every line ends with EOL. There is no specific EOL Every line ends with EOL.
character.
Conversion taken place from No conversion taken place Conversion taken place from
ASCII/UNICODE to Binary ASCII/UNICODE to Binary
while presenting while presenting
Operations on a file
File handling takes the following operations in sequence
 Opening of a file  Read or write (perform operation)  Closing of the file

File Naming convention


A file name generally consists of 2 parts viz. primary and Extension. However, extension is optional.
Extension such as .txt for text file, .exe for executable file, .jpg for image file, .mpg for sound file etc can be
used. The length of filename and its extension is platform dependant. Some specific characters are restricted
to use in file name.

Std. XII (SCIENCE) 1


MODERN OXFORD PUBLIC SCHOOL, BAM [CS MATERIAL]
Path
A path is a string that specifies to a unique location in a file system. It is used to represent directory or file
relationships. The directory hierarchy is separated by delimiters like backslash („\‟) or forwardslash („/‟) and
is File System dependent.
If you are using MSDOS or Windows file system, use \\ in the path; as \ is treated as escape sequence. By
using “r” before path, ignore applying \\.
Types of Path
 Absolute Path – It is a full path of the file from the root directory regardless of the current
working directory.
 Relative Path – It is the path of the file from the current working directory.
Relative path specifiers

\ specifies to root directory


. specifies to current directory
.. specifies to parent directory
..\.. specifies to Parent, parent, directory
..\..\.. specifies to parent, parent, parent directory and so on.
While specifying to sibling or descendant (sub-directories) you must name the directory in the path.

C (Root Directory)
:
demo

folder1 folder2 folder3


file1.txt

folder4 folder5 folder6 folder7


file3.txt file4.txt
file2.txt

file5.txt file6.txt file7.txt file8.txt file9.txt

Opening a file
Syntax:
Fileobject = open(“filename”,”mode”)

Std. XII (SCIENCE) 2


MODERN OXFORD PUBLIC SCHOOL, BAM [CS MATERIAL]
Modes of opening a file
Mode specifies the purpose of opening a file.
Mode Description
Open a file for reading. (default) . If file does not exist raises error. File pointer is at the
'r'
beginning of file.
Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
'w'
File pointer is at the beginning of file
Open a file for exclusive creation. If the file already exists, the operation fails. File pointer
'x'
is at the beginning of file.
Open a file for appending at the end of the file without truncating it. Creates a new file if it
'a'
does not exist. File pointer is at the end of file.
Open a file for both reading and writing. If file does not exist raises error. File pointer is at
„r+‟
the beginning of file.
Open a file for both writing and reading. Creates a new file if it does not exist or truncates
„w+‟
the file if it exists. File pointer is at the beginning of file
Open a file for appending. Creates a new file if it does not exist. Otherwise writes new data
„a+‟
at the end of file. File pointer is at the end of file.
't' Open in text mode. (default)
'b' Open in binary mode.

Example:
f = open("test.txt") # equivalent to 'r' or 'rt'
f = open("test.txt",'w') # write in text mode
f = open("test.txt",'wb') # write in text mode
f = open("img.bmp",'r+b') # read and write in binary mode

Closing a file
File must be closed when all operations are over. Closing a file will free up the resources that were tied with
the file and is done using Python close() method.
Syntax:
Fileobject.close()
However, if a file is opened using “with” statement, the file is implicitly closed when the block of statement
is over. For ex.
with open("filename",”mode”) as f:
# perform file operations
This ensures that the file is closed when the block inside with is exited. We don't need to explicitly call the
close() method. It is done internally.

Handling text file


Reading data from a text file
Methods Description
Var =fobj.read() Reads entire contents as string.
Var=fobj.read(n) Reads n bytes as string.
Var= fobj.readline() Reads a line at a time as string
Var=fobj.readlines() Reads all lines as list of strings

Std. XII (SCIENCE) 3


MODERN OXFORD PUBLIC SCHOOL, BAM [CS MATERIAL]
Writing data into a text file
Methods Description
Fobj.write(string) Writes a string into file.
Fobj.writeline(list) Writes a list of strings.

Example#1
Write a program to read the contents of a text file.
f=read(„story.txt‟,‟r‟)
d=f.read()
print(d)
f.close()

Example#2
Write a program to read the contents of a text file and print character by character.
f=read(„story.txt‟,‟r‟)
d=f.read()
for i in d:
print(i)
f.close()

Example#3
Write a program to read the contents of a text file and print words.
f=read(„story.txt‟,‟r‟)
d=f.read()
w=d.split()
for i in w:
print(i)
f.close()

Example#4
Write a program to read the contents of a text file and print line by line.
f=read(„story.txt‟,‟r‟)
lns=f.readlines()
for ln in lns:
print(ln)
f.close()

OR
Std. XII (SCIENCE) 4
MODERN OXFORD PUBLIC SCHOOL, BAM [CS MATERIAL]
f=open("story.txt","r")
while True:
a=f.readline()
if len(a)<=0:
break
print(a)
f.close()
Example#5
Write a program to read data from keyboard and store in a file.
f=read(„story.txt‟,‟w‟)
if not f:
print(“File can‟t be created”)
else:
nm=input(“Enter your name:”)
f.write(nm)
age=input(“Enter your age:”)
f.write(age)
f.close()

EXERCISE
1. Write a program to accept strings and store in a text file named „myfile1.txt‟ in 2
d:\<yourname> folder.
2. Write a program to read the contents of the file “myfile1.txt”. 2
3. Write a program to read the 1st 20 characters of the file “myfile1.txt”. 2
4. Write a program to read the contents of the file “myfile1.txt” line by line. 2
5. Write a function in PYTHON to count the no. of vowels (ignore case) present in a text file " 2
myfile1.txt ".
6. Write program to count no. of words in a text file named “myfile1.txt”. 2
7. Write program to read the content of a text file myfile1.txt, and display the words with 3 2
character in length.
8. Write a program to read contents of a text file named myfile1.txt, count and display the 2
occurrence of a given word. Note :
‐ The word should be an independent word
‐ Ignore type cases (i.e. lower/upper case)
9. Write a program that reads the contents of a text file story.txt and counts the words You and 2
Me (not case sensitive)(not whole word)
10. Write a program in PYTHON to read the content of a text file "DELHI.TXT' and display all 2
those lines on screen, which are either starting with 'D' or starting with 'M'.
11. Write a program in PYTHON to count the no. of vowels (ignore case) present in a text file 2
"STORY. TXT" line wise.
12. Write a program in PYTHON to count the no. of lines, tabs, whitespaces, upper cases, 2
lowercase and digits present in a text file "STORY. TXT".
13. Write a function in PYTHON to read the content of a text file "DELHI.TXT' and copy only 2
those lines started with „I‟ into a new file named „NewDelhi.txt‟

Std. XII (SCIENCE) 5


MODERN OXFORD PUBLIC SCHOOL, BAM [CS MATERIAL]
The flush ()
When you write onto a file using write (), data are stored in buffer and pushes it into actual file on storage
device later on. If however, you want to force to write the contents of buffer to storage, use flush().
HANDLING BINARY FILE
Binary files are any files where the format isn't made up of readable characters. The data of binary file are
processed by CPU internally and present to a human understandable form through a particular program or
application.

Binary files can range from image files like JPEGs or GIFs, audio files like MP3s or binary document
formats like Word or PDF.
Binary files are less in size as compared to text file for the same data, due to its‟ internal representation. For
example if we wants to store 234556 in a text file it occupied 6 bytes (a byte for each digits), where as in
binary mode it is 4 byte only, because in Memory it is represented as integer.

In Text mode, data are stored in a platform-dependent encoding format (ASCII or Unicode, UTF8 etc). This
mode is about conversion of line endings.
On the other hand, Binary mode data are stored in the same format as in memory (raw). No translation or
encoding applied while rendering data.
The pickle module

“Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and
“unpickling” is the inverse operation, whereby a byte stream (from a binary file or bytes-like object) is
converted back into an object hierarchy. Pickling is alternatively known as “serialization”, “marshalling”.
The reverse process, which takes a stream of bytes and converts it back into a data structure, is called
deserialization or unmarshalling.

Pickle module has the following methods to handle file. You have to import the module before calling the
methods.

Writing data to binary file.


Syntax:
pickle.dump(datavariable,fileobject)
Reading from binary file.
Syntax:
var = pickle.load(fileobject)
Unlike read() in text file, the load method does not, reads entire data at a time. It reads one block of data at a
time.
Exception handling while reading.
While reading the file pointer may encounter EOF and raises the EOFError. You can handle the exception
using try…. except block.
Handling exceptions
There may be errors while handling a file. Hence, it is safer to use try…. Finally block.
try:
f = open("test.txt",encoding = 'utf-8')
# perform file operations
except:
# error handler
finally:
# task to clean up
Std. XII (SCIENCE) 6
MODERN OXFORD PUBLIC SCHOOL, BAM [CS MATERIAL]
Example #1
Write a python program to store the following student data in a binary file.
sid,sname,sclass,section
import pickle
f=open(“stud.dat”,”wb”)
sid=int(input(“Enter ID:”))
snm=input(“Enter Name:”)
sc=input(“Enter Class :”))
sec=input(“Enter section:”)
d=[sid,snm,sc,sec]
pickle.dump(d,f)
f.close()

Example #2
Write a python program to read data earlier stored in the binary file stud.dat.
sid,sname,sclass,section

import pickle
f=open(“stud.dat”,”rb”)
try:
while True:
d=pickle.load(f)
print(d)
except:
pass
f.close()

1 1. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price]. 2


i. Write a user defined function CreateFile() to input data for a record and add to Book.dat .
2 ii. Write a function CountRec(Author) in Python which accepts the Author name as parameter 2
and count and return number of books by the given Author are stored in the binary file
“Book.dat”.
3 A binary file “STUDENT.DAT” has structure (admission_number, Name, Percentage). Write 2
a function countrec() in Python that would read contents of the file “STUDENT.DAT” and
display the details of those students whose percentage is above 75. Also display number of
students scoring above 75%.

Std. XII (SCIENCE) 7


MODERN OXFORD PUBLIC SCHOOL, BAM [CS MATERIAL]
4 Considering the following structure of FACTORY[FCTID, FCTNM, PROD], write a method 2
in Python to search and display the content in a pickled file FACTORY.DAT, where FCTID
is matching with a give value.
5 Consider the following structure of Student[admno, name]. Write a method in python to write 2
the content in a pickled file student.dat.
6 Write a function COSTLY( ) to read each record of a binary file GIFTS.DAT, find and 2
display those items, which are priced more than 2000. Assume that the file GIFTS.DAT is
created with the following structure Gift[code,item,price].
7 Write a function Result( ) to read each record of a binary file STUDENT.DAT, find and 2
display result of all students base on the following condition. Assume that the file
STUDENT.DAT is created with the following structure student [SID,SNAME, phy_mark,
Chem_mark, Maths_mark].
% of mark Result
35-49 3rd
50-59 2nd
>=60 1st
otherwise fail
8 Write a definition for function BUMPER() read each record of a binary file GIFTS.DAT, find 2
and display details of those gifts, which has remarks as “on discount”. Assume that the file
GIFTS.DAT is created with the help of following structure
GIFTS[ID,GNAME,REMARK,PRICE]
Random Access
Whenever you open a file in read mode the file pointer is at the beginning of the file. However you can
move the file pointer to any location and then perform an operations. There are 2 methods to handle file
pointer.
1. Var=Fobj.tell() returns the current position of file pointer
2. Fobj.seek(offset,[,mode]) moves the file pointer to a particular position.
Where:
Offset : is a number specifying number of bytes to move. (+ve for forward move, -ve for backward move)
Mode: is a number specifying position of a file
0 for beginning,1 for current position and2 for end of file.
9. Write a program to display the size in bytes of a file. 2
10. Write a program to modify the mark in English to 80 of student id 8. 2
11. Write a program to add 5 mark in English of all student whose mark >=50. 2

HANDLING CSV FILE


A CSV file (Comma Separated Values file) is a type of plain text file (ASCII) that uses specific structuring
to arrange data in tabular form. The tabular data consists of rows and columns where each row represents a
record (data related to an object) and each column represents a field or an attribute of an object.

Structure of CSV file


Normally, CSV files use a comma to separate each specific data value. Here‟s what that structure looks like:

ColumnName1 ,ColumnName2, CcolumnName3

Std. XII (SCIENCE) 8


MODERN OXFORD PUBLIC SCHOOL, BAM [CS MATERIAL]
first row data 1,first row data 2,first row data 3
second row data 1,second row data 2,second row data 3
...........................................................................
………………………………………………….
 Normally, the first line identifies the name of a data column.
 Every subsequent line represents actual data.

The csv module


csv module in python is used to handle a csv file. You have to import the module before calling the methods.
Reading data from csv file.

csv_reader = csv.reader(fobj) returns<class '_csv.reader'>csv reader is a list of


records.
csv_reader = csv.DictReader(fobj) Reading data as dictionary

Example:
import csv
f=open("d:/book1.csv")
csv_reader = csv.reader(f)
for row in csv_reader:
print(row)
f.close()

Note : Other than comma (,) , the separator character or delimiter may be the tab, colon (:) and semi-colon
(;) characters etc. Properly parsing a CSV file requires us to know which delimiter is being used.

csv_reader = csv.reader(cf,delimiter=‟:‟)

Writing data to a csv file.


fwriter = csv.writer(fobj, delimiter=',') Creates a writer object
fwriter.writerow(list | dictionary) Writerow() writes data intto file
fieldnames = ['Name', 'Gender', 'City'] Write data as dictionary
writer = csv.DictWriter(fobj, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'Name': 'Santosh Kumar Panda', 'Gender':
'Male', 'City': 'Berhampur'})

Example #
import csv
with open(r'd:\samplecsv2.csv', mode='w') as f:
fwriter = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
fwriter.writerow(['Name', 'Gender', 'City'])
fwriter.writerow(['SangramKishor Dash', 'Male', 'Berhampur'])
fwriter.writerow(['Nigam Prasad', 'Male', 'Bhubaneswar'])
fwriter.writerow(['ArpitaKumari Mishra', 'Female', 'Cuttack'])
Std. XII (SCIENCE) 9
MODERN OXFORD PUBLIC SCHOOL, BAM [CS MATERIAL]
Example #2
import csv
with open(r'd:\samplecsv3.csv', 'w') as fc:
fieldnames = ['Name', 'Gender', 'City']
writer = csv.DictWriter(fc, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'Name': 'Santosh Kumar Panda', 'Gender': 'Male', 'City': 'Berhampur'})
writer.writerow({'Name': 'Ganesh Pradhan', 'Gender': 'Male', 'City': 'Kolkota'})

1 Write a program in python to write the STUDENT data in a csv file named “student.csv” with 2
following structure. [sid,sname,Sclsss,eng,maths]
2 Write a program in python to read and display the sid and name of students who has obtained 2
>50 in English form a csv file “student.csv”.
3 Write a program in python to read and display the details with total and percentage of mark 2
who has obtained more than 60% form a csv file “student.csv”.

Std. XII (SCIENCE) 10


MODERN OXFORD PUBLIC SCHOOL, BAM [CS MATERIAL]
Multiple Choice Answer Type Questions (1 Marks) 11. Which of the following statements are true?
1. Which of the following is the default mode of a) When you open a file for reading, if the
opening a file? file does not exist, an error occurs
a. „r‟ b. „w‟ b) When you open a file for writing, if the
c. „a‟ d. None of these file does not exist, a new file is created
2. Which of the following is the default mode of c) When you open a file for writing, if the file
opening a file? exists, the existing file is overwritten with
a. „b‟ b. „t‟ the new file
c. „c‟ d. None of these d) All of the mentioned
3. Which of the following method, reads entire 12. Which function is used to read all the
content at a time from a text file? characters?
a. read() b. read(n) a) Read() b) Readcharacters()
c. readline() d. None of these c) Readall() d) Readchar()
4. The read() without parameter reads data 13. Which function is used to read single line
from a file and returns a from file?
a. int b. string a) Readline() b) Readlines()
c. list d. dictionary c) Readstatement() d) Readfullline()
5. The read(n) returns n bytes from a text file 14. Which function is used to write all the
and return as characters?
a. int b. string a) write() b) writecharacters()
c. list d. dictionary c) writeall() d) writechar()
6. The readline() reads contents of a text file 15. Which function is used to write a list of
a. One line at a time and return as string string in a file?
b. Multiple lines at a time and return as list of a) writeline() b) writelines()
strings c) writestatement() d) writefullline()
c. One line at a time and return as list of 16. Which function is used to close a file in
strings python?
d. Multiple lines at a time and return as string a) Close() b) Stop()
7. The readlines() reads contents of a text file c) End() d) Closefile()
and return as
17. Which of the following are the modes of
a. string b. list of strings
both writing and reading in binary format in
c. tuples d. dictionary file?
8. Which of the following(s) is correct to open a a) wb+ b) w
file c:\scores.txt for reading? c) wb d) w+
a. infile = open(“c:\scores.txt”, “r”) 18. Which of the following is not a valid mode
b. infile = open(“c:\\scores.txt”, “r”) to open a file?
c. infile = open(file = “c:\scores.txt”, “r”)
a) ab b) rw
d. infile = open(file = “c:\\scores.txt”, “r”)
c) r+ d) w+
9. Which of the following is incorrect to open a 19. What is the difference between r+ and w+
file c:\scores.txt for writing?
modes?
a) outfile = open(r“c:\scores.txt”, “w”)
a) no difference
b) outfile = open(“c:\\scores.txt”, “w”)
c) outfile = open(file = “c:\scores.txt”, “r”) b) in r+ the pointer is initially placed at the
d) outfile = open(file = “c:/scores.txt”, “w”) beginning of the file and the pointer is at
10. Which of the following opens a file the end for w+
c:\scores.txt for appending data c) in w+ the pointer is initially placed at the
a) outfile = open(“c:\\scores.txt”, “a”) beginning of the file and the pointer is
b) outfile = open(“c:\\scores.txt”, “rw”) at the end for r+
c) outfile = open(file = “c:\scores.txt”, “w”) d) depends on the operating system
d) outfile = open(file = “c:\\scores.txt”, “w”)
Std. XII (SCIENCE) 11
MODERN OXFORD PUBLIC SCHOOL, BAM [CS MATERIAL]
20. How do you get the current position within 30. Which of the following represents mode of
the file? both reading and writing in a binary
a) fp.seek() b) fp.tell() format?
c) fp.loc d) fp.pos a. wb+ b. w
21. How do you change the file position to an
c. wb d. w+
offset value from the start?
31. Which of the following is not a valid mode
a) fp.seek(offset, 0)
to open a file?
b) fp.seek(offset, 1)
c) fp.seek(offset, 2) a. ab b. rw
d) none of the mentioned c r+ d. w+
22. What happens if no arguments are 32. Which is the default delimiter in a csv file?
passed to the seek function? a. ; (semicolon) b. ,(comma)
a) file position is set to the start of file
c. \t (tab) d. \n (new line)
b) file position is set to the end of file
c) file position remains unchanged 33. Which character represents the EOL
d) error translation in csv file?
23. What is the full form of csv? a. \n b. \r\n
a) comma separation value c. \t d. None of these
b) comma separated value 34. Which of the correct method of writing
c) comma syntax value data in a binary file?
d) comma separated variable
a. pickle.dump(fileobj,datavar)
24. In which mode the file pointer moves to
the end of file, so that the existing b. pickle.dump(datavar,fileobj)
contents not overwritten? c. pickle.load(fileobj)
a. „r‟ b. „w‟ d. pickle.load(datavar)
c. „a‟ d. Both a and b 35. Which of the following is correct way to
25. Identify the invalid mode from the check the age of student in the following
followings code, if the data of students are stored in
a) a b) r+ the following format?
c)ar+ d)w {„sid‟:1,‟sname‟:‟satya‟,‟age‟:35,‟gender‟:
26. To read 10 characters from a file object ‟M‟}
infile, we use ____________ d= pickle.load(fobj)
a) infile.read(10) b) infile.read()
a. if d[2] >25
c) infile.readline(10) d) infile.readlines()
27. To read the entire remaining contents of b. if d[„age‟]> 25
the file as a string from a file object infile, c. Both a and b
we use ____________ d. None of these
a) infile.read(10) b) infile.read() 36. Which of the following is correct way to
c) infile.readline() d) infile.readlines() check the age of student in the following
28. To read the next line of the file from a file code, if the data of students are stored in
object infile, we use ____________ the following format?
a) infile.read(2) b) infile.read()
[1,‟satya‟,35,‟M‟]
c) infile.readline() d) infile.readlines()
d= pickle.load(fobj)
29. Which of the following method writes a
string in a text file? a. if d[2] >25
a. read() b. write() b. if d[„age‟]> 25
c. writelines() d. writeline() c. Both a and b
d. None of these
Std. XII (SCIENCE) 12
MODERN OXFORD PUBLIC SCHOOL, BAM [CS MATERIAL]
37. What is the use of tell() method in python? Very Short Answer Type Questions : (1 Marks)
a) tells you the current position within the 1.

1. What is the advantages of using „with


file open()‟ ?
b) tells you the end position within the file 2. What is the use of flush() in file handing?
c) tells you the file is opened or not 3. What is the importance of closing an
d) none of the mentioned opened file after use?
38. What is the use of seek() method in files? 4. What do you mean by serialization /
a) sets the file‟s current position at the marshalling/ pickling and un-serialization/
offset un-marshalling/ unpickling?
b) sets the file‟s previous position at the 5. What is the use of seek() and tell() in
offset random accessing of a file ?
c) sets the file‟s current position within the 6. What do you mean by delimiter? Which
file character can be delimiter in a CSV file?
d) none of the mentioned
39. What is the default value of whence in the Short Answer Type Questions : (2 Marks)
2.

seek(offset[,whence]) method? 1. Differentiate between text file and binary


a) 0 file.
b) 1 2. What are the differences between opening
c) 2 a file in r+ and w+ mode?
3. What do you mean by mode? What are the
d) none of these
different modes in opening a file?
40. The value 1 indicates to _______in the 4. What is CSV file? What are the advantages
whence ofseek(offset[,whence]) method? of using it?
a) beginning of file
Case Based Questions : (4 Marks)
b) current location of file
Q1. Vedansh is a Python programmer working
c) end of file
in a school. For the Annual Sports Event, he
d) none of these
has created a binary file „Result.dat‟ with
41. What is the pickling?
[Student_Id, St_Name, Game_Name] and
a) It is used for object serialization
Result to store the results of students in
b) It is used for object deserialization
different sports events.
c) None of the mentioned
After the event has been completed, he now
d) All of the mentioned
wants to display the records of those
42. What is unpickling?
students who won the game, which is
a) It is used for object serialization
inserted in the Result field with „Won‟ and
b) It is used for object deserialization
„Loss‟ data. As a Python expert, help him
c) None of the mentioned
d) All of the mentioned complete the following code based on the
requirement given above.
43. Correct syntax of file.writelines() is?
import ___________ #Statement1
a) file.writelines(sequence)
b) fileObject.writelines() rec=[]
c) fileObject.writelines(sequence) while True:
d) none of the mentioned Student_Id=int(input("Enter Student Id:"))
45. Correct syntax of file.readlines() is? St_name=input("Enter name:")
a) fileObject.readlines(sizehint ); Game_Name=input("Enter Salary:")
b) fileObject.readlines(); Result= input(“Enter Result:”)
c) fileObject.readlines(sequence) data=[Student_Id, St_Name,
d) none of the mentioned Game_Name,Result]

Std. XII (SCIENCE) 13


MODERN OXFORD PUBLIC SCHOOL, BAM [CS MATERIAL]
rec.append(data) fin=open("record.dat","rb")
Choice=input("Wish to enter more fout=open("__________") #Statement 2
records: Y/N") found=False
if Choice.upper()=='N': eid=int(input("Enter employee id to
break update theirsalary :: "))
f1=_____________#Statement2 while True:
pickle.dump(rec,f1) try:
print("Record added:") rec=______________ #Statement 3
fout=open("Result.dat",'rb') if rec["Employee id"]==eid:
res=________________ #Statement 3 found=True
count=0 rec["Salary"]=int(input("Enter new
for i in res: salary :: "))
if _____________: #Statement 4 pickle.____________ #Statement 4
st_id=i[0] else:
st_name=i[1] pickle.dump(rec,fout)
game=i[2] except:
result=i[3] break
count+=1 if found==True:
print(st_id,st_name,game,result) print("The salary of employee id ",eid,"
print("Total students are", count) has been updated.")
fout.close() else:
(i) Write a statement to import the module. print("No employee with such id is not
(Statement 1) found")
(ii) Write a statement to open a binary file in fin.close()
append mode. (Statement 2) fout.close()
(iii) Write the correct statement required to load (i) Which module should be imported in the
the file. (Statement 3) program? (Statement 1)
(iv) Write a statement to check if result field (ii) Write the correct statement required to open
contains „Won‟ or „won‟. (Statement4) a temporary file named temp.dat.
Q2. Aman is a Python programmer. He has (Statement 2)
written a code and created a binary file (iii) Which statement should Aman fill in
record.dat with employeeid, ename and Statement 3 to read the data from the binary
salary. The file contains 10 records. He now file, record.dat and in Statement 4 to write
has to update a record based on the the updated data in the file, temp.dat?
employee id entered by the user and update Q3. Rohit, a student of class 12, is learning CSV
the salary. The updated record is then to be File Module in Python. During examination,
written in the file temp.dat. The records he has been assigned an incomplete python
code (shown below) to create a CSV File
which are not to be updated also have to be
'Student.csv' (content shown below). Help
written to the file temp.dat. If the employee him in completing the code which creates
id is not found, an appropriate message the desired CSV File
should to be displayed. As a Python expert, 1,AKSHAY,XII,A
help him to complete the following code 2,ABHISHEK,XII,A
based on the requirement given above: 3,ARVIND,XII,A
import _______ #Statement 1 4,RAVI,XII,A
5,ASHISH,XII,A
def update_data():
import _____ #Statement-1
rec={}
Std. XII (SCIENCE) 14
MODERN OXFORD PUBLIC SCHOOL, BAM [CS MATERIAL]
fh = open(_____, _____, newline='') #Statement-2 Help her in completing the code to read the
stuwriter = csv._____ #Statement-3 desired CSV file named “employee.csv”.
data = [ ] ENO,ENAME,DEPARTMENT
header = ['ROLL_NO', 'NAME', 'CLASS', E1, JAGAN PANDA , ACCOUNTS
'SECTION'] E2, SIMANCHAL PRADHAN,
data.append(header) PRODUCTION
for i in range(5): E3,SWASTIK SHARMA,MARKETING
roll_no = int(input("Enter Roll Number : ")) E4, NIROJ DAS, HUMAN RESOURCES
name = input("Enter Name : ") #Incomplete code with error
Class = input("Enter Class : ") import CSV #statement 1
with open(_______,______,newline=‟‟) as
section = input("Enter Section : ")
File: # statement 2
rec = [ _____ ] #Statement-4
ER=csv. ________ #statement 3
data.append(_____) #Statement-5
for R in range(ER): #statement 4
stuwriter. _____ (data) #Statement-6 if ________ == “ACCOUNTS” :
fh.close() #statement 5
i. Identify the suitable code for blank space in the print(_______,______) #statement 6
line marked as Statement-1. i. Nisha gets an error for the module name
a) csv file b) CSV used in statement 1. What should she write
c) csv d) cvs in place of CSV to import the correct
ii. Identify the missing code for blank space in module?
line marked as Statement-2. a. file b. csv
a) "Student.csv","wb" b) "Student.csv","w" c. Csv d. pickle
c) "Student.csv","r" d) "Student.cvs","r" b. Identify the missing code for the blank
iii. Choose the function name (with argument) that spaces in statement 2 to open the mentioned
should be used in the blank space of line file.
marked as Statement-3. a. “employee.csv”,”r”
a) reader(fh) b) reader(MyFile) b. “employee.csv”,”w”
c) writer(fh) d) writer(MyFile) c. “employee.csv”,”rb”
d. “employee.csv”,”wb”
iv. Identify the suitable code for blank space in ine
c. Choose the function name (with parameter)
marked as Statement-4.
a) 'ROLL_NO', 'NAME', 'CLASS', 'SECTION' that should be used in the statement 3.
b) ROLL_NO, NAME, CLASS, SECTION a. reader(File) b. readrows(File)
c) 'roll_no','name','Class','section' c. writer(File) d.wirterows(File)
d) roll_no,name,Class,section d. Nisha gets an error in statement 4. What she
iv. Identify the suitable code for blank space in the should write to correct the statement?
line marked as Statement-5. a. for R in ER:
a) data b) record b. while R in range(ER):
c) rec d) insert c. for R =ER:
v. Choose the function name that should be used d. while R== ER:
in the blank space of line marked as Statement- e. Identify the suitable code for statement 5 to
6 to create the desired CSV File? match every rows‟ 3rd property with
a) dump() b) load() “ACCOUNTS”
c) writerows() d) writerow() a. ER[3] b. ER[2]
Q4. Nisha, an intern in ABC Pvt. Ltd. Is c. R[2] d. R[3]
developing a project using the csv module in f. Identify the suitable code for statement 6 to
python. She has partially developed the code display every employee‟s name and
as follows leaving out statements about corresponding department
which she is not very confident. The code a. ER[1],R[2] b. R[1], ER[2]
also contains error in certain statements. c. R[1], R[2] d. ER[1], ER[2]

Std. XII (SCIENCE) 15

You might also like