DATA FILE HANDLING

DATA FILE HANDLING


File- A file is a sequence of bytes on the disk/permanent storage where a group of related

data is stored. File handling in Python enables us to create, update, read, and delete the

files stored on the file system through our python program.

Data File handling takes place in the following order.

1- Opening a file.

2- Performing operations (read, write) or processing data.

3- Closing the file.

Types of File in Python:

Python allows us to create and manage three types of data files.

1- Text file

2- Binary file

3- CSV file

Text file: A text file is simply a sequence of ASCII or Unicode characters. A line is a sequence of characters, stored in permanent storage. In a text file, each line is terminated by a special character, known as End of Line (EOL). Text files can be created using any text editor.     Ex. Myfile.txt.

Binary file: A binary file stores the data in the same way as stored in the memory. The .exe

files, mp3 file, image files, word documents are some of the examples of binary files. We

can’t read a binary file using a text editor.

CSV file: CSV (Comma Separated Values) is a simple text file format for storing data in

tabular form such as spreadsheet or database. The data is organised with one record on

Each line and each field is separated by comma.


Compare text files, binary files and csv files


S.No

Text file

Binary file

CSV file

1

It is capable to handle

textual data.

It is capable to handle large

file.

It is very common format

and platform independent.

2

It consists of series of

lines of a set of letters,

numbers or symbols

(String)

It consists of data with a

specific pattern without any

delimiter.


It consists of plain text with

a list of data with a delimiter.


3

Any text editors like

notepad can be used to

read them.


No specific programs can be

used to read them, python

provides functions to read

data.

It can be read using text

editors like notepads and

spreadsheet software.

4

Every line ends with EOL.

There is no specific EOL

character.

It terminates a  line automatically

when the delimiter is not used after data.



Absolute Path – It is a full path of the file from the root directory. Absolute paths ensure

that Python can find the exact file on your computer.

Ex : - C:\\Users\\Tanmay\\Desktop\\Delete\\file_handling.txt

f=open(“C:\\Users\\Tanmay\\Desktop\\Delete\\file_handling.txt”,r)


Relative Path – It is the path of the file from the current working directory.

Relative Path is the hierarchical path that locates a file or folder on a file system starting

from the current directory. The relative path is different from the absolute path, which

locates the file or folder starting from the root of the file system.

f=open(“file_handling.txt”,r)


Operation On Files In Python


1. Opening a file – open() function

2.Read/Write file

– Read Functions – read() , readline(), readlines()

– Write Functions – write() , writelines()

3.Close the File – close() Function

4.Remove the file – remove() #Function of OS Module

5.Rename the file –rename(“oldname”,”newname”) #Function of OS Module


Read the Contents of An Existing File

1. Open the file–


file_object = open(“read_sample.txt”, ’r’) # Relative Path

file_object = open(“C:\\Desktop\\Notes\\sample.txt”) #Absolute Path


2. Reading the file–


rf = file_object.read()

print(rf)


3. Closing the file–


file_object.close()


Working of open() function

We use open () function in Python to open a file in read or write mode. open ( ) will return

a file object. To return a file object we use open() function along with two arguments, that

accepts file name and the mode, whether to read or write. So, the syntax being:

open(filename, mode). There are three kinds of mode, that Python provides and how files

can be opened:


“ r “, for reading.

“ w “, for writing.

“ a “, for appending.


Modes Description

1. r - Opens a file for reading only. The file pointer is placed at

the beginning of the file. This is the default mode. Gives error if file does not exist.

2. r+ - Opens a file for both reading and writing. The file pointer

placed at the beginning of the file.

3. w - Opens a file for writing only. Overwrites the file if the file

exists. If the file does not exist, create a new file for writing.

4. w+ - Opens a file for both writing and reading. Overwrites the

existing file if the file exists. If the file does not exist, creates a new file for reading and

writing.

5. a - Opens a file for appending. The file pointer is at the end of

the file if the file exists. That is, the file is in the append mode. If the file does not exist, it

creates a new file for writing.

6. a+ - Opens a file for both appending and reading. The file

pointer is at the end of the file if the file exists. The file opens in the append mode. If the

file does not exist, it creates a new file for reading and writing.


Reading from a file


There are three ways to read data from a text file.

read() : Returns the read bytes in the form of a string. Reads n bytes, if no n specified, reads

the entire file.

File_object.read([n])

readline() : Reads a line of the file and returns in form of a string. For specified n, reads at

most n bytes. However, does not reads more than one line, even if n exceeds the length

of the line.

File_object.readline([n])

readlines() : Reads all the lines and return them list in which each line as a string element.

File_object.readlines()

Note: ‘\n’ is treated as a special character of two bytes.

Writing onto text files:

write() function

The write() function will write the content in the file without adding any extra characters.

file_name.write(content)

writelines() function

This function writes the content of a list to a file. file_name.

writelines(list_of_lines)

# Program to show various ways to read data from a file.

# Creating a file

file1 = open("myfile.txt", "w")

L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]

# Writing data to a file

file1.write("Hello \n")

file1.writelines(L)

file1.close()

# to change file access modes file1 = open("myfile.txt", "r+")

print("Output of Read function is ")

print(file1.read())

print()

# seek(n) takes the file handle to the nth

# byte from the beginning.

file1.seek(0)

print("Output of Readline function is ")

print(file1.readline())

print()

file1.seek(0)

# To show difference between read and readline

print("Output of Read(9) function is ")

print(file1.read(9))

print()

file1.seek(0)

print("Output of Readline(9) function is ")

print(file1.readline(9))

print() file1.seek(0)

Output:

Output of Read function is

Hello

This is Delhi

This is Paris

This is London

Output of Readline function is

Hello

Output of Read(9) function is

Hello

Th

Output of Readline(9)

function is

Hello


Output of Readlines function is

['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']



Setting Offsets in a File


If we want to access data in a random fashion, then Python gives us seek() and tell()

functions to do so


The tell() method


This function returns an integer that specifies the current position of the file object in the

file. The position so specified is the byte position from the beginning of the file till the

current position of the file object. The syntax of using tell() is:

A=file_object.tell()


The seek() method

This method is used to position the file object at a particular position in a file. The syntax

of seek() is:

file_object.seek(offset [, reference_point])


In the above syntax, offset is the number of bytes by which the file object is to be moved.

reference_point indicates the starting position of the file object. That is, with reference to

which position, the offset has to be counted. It can have any of the following values:

0 - beginning of the file

1 - current position of the file

2 - end of file

By default, the value of reference_point is 0, i.e. the offset is counted from the beginning

of the file.

For example, the statement fileObject.seek(5,0) will position the file object at 5th byte

position from the beginning of the file.



PRACTICE QUESTIONS

1. Write a program to read contents from the text file story.txt and count no:of

vowels in it

2. Write a program to read contents from the text file myfile.txt and find average

word count

3. Write a program to read contents from the text file library.txt and count “is” as

independent word

4. Write a program to read contents from the text file diary.txt and count number of

lines with Starting letter “T” or “M”

5. Write a program to read contents from the text file mydiary.txt and count number

of lines with ending letter “r”


MULTIPLE CHOICE QUESTIONS

1. If a text file is opened in w+ mode, then what is the initial position of file

pointer/cursor?

a. Beginning of file

b. End of the file

c. Beginning of the last line of text file

d. Undetermined

2. Which of the following statements are true?

a. When you open a file for reading, if the file does not exist, an error occurs

b. When you open a file for writing, if the file does not exist, a new file is created

c. When you open a file for writing, if the file exists, the existing file is overwritten

with the new file

d. All of the mentioned

3. To read the entire remaining contents of the file as a string from a file object

myfile, we use

a. myfile.read(2)

b. myfile.read()

c. myfile.readline()

d. myfile.readlines()

4. A text file is opened using the statement f = open(‘story.txt’). The file has a total

of 10 lines. Which of the following options will be true if statement 1 and statement 2

are executed in order.

Statement 1: L1 = f.readline( )

Statement 2: L2 = f.readlines( )

a. L1 will be a list with one element and L2 will be list with 9 elements.

b. L1 will be a string and L2 will be a list with 10 elements.

c. L1 will be a string and L2 will be a list with 9 elements.

d. L1 will be a list with 10 elements and L2 will be an empty list.

5. Which function of a file object can be used to fetch the current cursor position in

terms of number of bytes from beginning of file?

a. seek( )

b. bytes( )

c. tell( )

d. fetch( )

6. What will be the output of the following code?


f = open(‘test.txt’, ‘w+’)

L = [‘First Line\n’, ‘Second Line\n’, ‘Third Line’]

f.writelines(L)

f.flush()

f.seek(0)

O = f.readlines()

print(len(O))


a. 33

b. 31

c. 28

d. 3

7. The contents of a text file named ‘quote.txt’ is as shown below:


All the kings horses and all the kings men

cannot fix what isn’t broken.



What will be the output of the following code?

fin = open('fracture.txt’)

data = fin.read(10)

print(data[0:3], end= ‘’)

data = fin.readline(5)

print(data[0:3] , end= ‘’)

fin.seek(0)

data = fin.read(4)

print(data[0:3] , end= ‘’)


a. AllngsAll

b. AllcanAll

c. Allcancan

d. Allngscan


8. What will be the most correct option for possible output of the following code,

given that the code executes without any error.


f = open(‘cricket.txt’)

data = f.read(150)

print(len(data))


a. It will always be 150

b. 151

c. More than or equal to 150

d. Less than or equal to 150

9. For the following python code, what will be the datatype of variables x, y, z given

that the code runs without any error?

f = open(‘story.txt’)

x = f.read(1)

y = f.readline()

z = f.readlines()

a. string, list, list

b. None, list, list

c. string, string, list

d. string, string, string


10. The contents of a text file named ‘fracture.txt’ is as shown below:


Do you dare stay out, Do you dare go in

How much can you lose, How much can you win

And if you go in, should you turn left or right

You will get so confused that you will start in to race




What will be the output of the following code?

fin = open('fracture.txt’)

x = 0

for line in fin:

words = line.split( )

for w in words:

if len(w)>x:

x = len(w)

print(x)


a. 12

b. 11

c. 13

d. 10


Answers:

1. a. Beginning of file

2. d. All of the mentioned

3. b. myfile.read()

4. c. L1 will be a string and L2 will be a list with 9 elements.

5. c. tell( )

6. d. 3

7. a. AllngsAll

8. d. Less than or equal to 150

9. c. string, string, list

10. a. 12


VERY SHORT ANSWER TYPE QUESTIONS

1. Differentiate between file modes r+ and w+ with respect to python?

Ans: r+ opens a text file for reading and writing.

w+ opens a text file for reading and writing. It overwrites the file if it exists, create a file

if it doesn’t.

2. Write a statement in Python to open a text file “ABC.TXT” in reading mode.

Ans: F=open("ABC.TXT","r")

3. In ___________ files each line terminates with EOL or ‘\n’ or carriage return, or

‘\r\n’.

Ans: Text File

4. Observe the following code and answer the questions that follow.

File=open(“MyData”,”a”)

_____________ #Blank1

File.close()

a) What type (text/binary) of file is MyData ?

b) Fill the Blank1 with statement to write “ABC” in the file “Mydata”

Ans: a) Text File

b) File.write(“ABC”)

5. What are files?

Ans: A named entity, usually stored on a hard drive that contains a stream of

characters are called files.


SHORT ANSWER TYPE QUESTIONS

1. Explain seek() method in python.

In Python, seek() function is used to change the position of the File Handle to a given

specific position.

Syntax: fi.seek(offset, from_where), where fi is the file pointer

Offset: This is used for defining the number of positions to move forward.

from_where: This is used for defining the point of reference. It can take

0: beginning of the file. 1: current position of the file. 2: end of the file.


2. Write a function in Python that counts the number of “the” or “this” words

present in a text file “myfile.txt”.

Example: If the “myfile.txt” contents are as follows:

This is my first class on Computer Science. File handling is the easiest topic for me

and Computer Networking is the most interesting one.

The output of the function should be: Count of the/this in file: 3

Answer:

def displayTheThis():

num=0

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

N=f.read()

M=N.split()

for x in M:

if x=="the" or x== "this":

print(x)

num=num+1

f.close()

print("Count of the/this in file:",num)

3. Write a function countVowels() in Python, which should read each character of

a text file “myfile.txt”, count the number of vowels and display the count.

Example: If the “myfile.txt” contents are as follows:

This is my first class on Computer Science.

The output of the function should be: Count of vowels in file: 10

Answer:

def countVowels():

fobj = open(“myfile.txt”)

data = fobj.read()

count = 0

vowels=[‘a’,’e’,’I’,’o’,’u’]

for ch in data:

if ch in vowels:

count +=1

print(“Count of vowels in file:”, count)


4. Write a Python program to count all the line having 'a' as last character.

Answer:

count =0

f=open('fracture.txt',"r")

data=f.readlines()

for line in data:

if line[-2] == 'a':

count=count+1

print("Number of lines having 'a' as last character is/are : " ,count)

f.close()

5. Assume that a text file named TEXT1.TXT already contains some text written into

it, write a program with a function named vowelwords(),that reads the file TEXT1.TXT

and create a new file named TEXT2.TXT ,which shall contain only those words from the

file TEXT1.TXT which don’t start with an uppercase vowel(i.e. with ‘A’,’E’,’I’,’O’,’U’) ,

for example if the file TEXT1.TXT contains

Carry Umbrella and Overcoat When it Rains

then the file TEXT2.TXT shall contain

Carry and when it Rains.

Answer:

def vowelwords ():

file1=open('TEXT1.txt','r')

file2=open('TEXT2.txt','w')

text = file1.read()

text=text.split()

vowels=['A','E','I','O','U']

for i in text:

if i[0] not in vowels:

file2.write(i)

file2.write(" ")

file1.close()

file2.close()

vowelwords()


BINARY FILES



● Binary file(used to store binary data such as images, video files, audio files

etc.) is a non-text file. It contains data as 1s and 0s(computer readable format).

● Binary files are processed byte by byte.

● There is no delimiter and EOL character in the binary file.

● There is no translations occur in binary files

● Binary files are faster in processing and consumes less memory compared to

text files.

● Extension of binary files are any non-text file exensions like .bin,.dat etc

● pickle module is offering functions(dump and load) to operating binary files.

● File opening mode must attach ‘b’ to it for operating binary file(Ex: ‘rb’-

for reading)







Operations on binary file


























try and except block

pickle.load() can generate runtime exceptions like EOFError. try and except

block will handle runtime errors raised due to EOF (end of file) .In try block write all the

statements that can generate an exception and in except block write code to handle the

exception.


Writing data into binary file

Searching of data

Modifying data

Deleting data

Appending data


Writing data into binary file


Searching of data from binary file

Deleting data from a binary file

Write a program to read contents from the file stud.dat and delete those records whose

marks <90. Assume stud.dat existing in the system with the record format

[rollno,name,marks]

Below program is implemented using function and module os is used to use functions

like rename() and remove()

Updating /Modifying data in a binary file

Write a program to update records in the file stud.dat with records in the format

[rollno,name,marks].Increase 10 marks to the student whose rollnumber entered by

the user

Appending data in to a binary file

Write a program to append records into the file stud.dat with records in the format

[rollno,name,marks]


Opening a file using with statement

In Python, we can also open a file using with statement.


The syntax of with statement is:

with open (file_name, access_mode) as file_object:

The with statement is a compact statement which combines the opening of file ,

processing of file along with inbuilt exception handling.The with statement will also close

the file automatically after with block is over.

with open(“myfile.txt”,”r+”) as myObject:

content = myObject.read()

Here, we don’t have to close the file explicitly using close() statement. Python

will automatically close the file.


SAMPLE QUESTIONS

1. A binary file “employees.dat” has structure [empid, empname, age, department]

a. Write a user defined function CreateEmployee() to input the data to a

record and add to employee.dat

b. Write a function CountRec(department) in Python which accepts the

Department of the employee as the parameter and count and return the

number of employees in that department.


PRACTICE QUESTIONS


1. A binary file “STUDENT.DAT” has structure [admission_number, Name, Percentage].

Write 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%.

2. A binary file “students.dat” has structure (admission_number, Name, Percentage,

subject). Write a function countrec() in Python that would read contents of the file and

display the details of those students whose subject is “Biology” and percentage is below

45%. Also display the number of such students

3. A binary file “STOCK.DAT” has structure [ITEMID, ITEMNAME, QUANTITY, PRICE].

(i) Write a user defined function MakeFile( ) to input data for a record and add to

Book.dat.

(ii) Write a function GetPrice(ITEMID) in Python which accepts the ITEMID as

parameter and return PRICE of the Item stored in Binary file STOCK.DAT

4. A binary file “EMPLOYEE.DAT” has structure (EMPID, EMPNAME, SALARY). Write a

function CountRec( ) in Python that would read contents of the file “EMPLOYEE.DAT”

and display the details of those Employees whose Salary is above 20000. Also display

number of employees having Salary more than 20000.

5. A binary file “Computers.dat” has structure [CNo, Make, Model, Price].

The description is given below:

CNo : Computer Number e.g. 278548

Make : Make of PC e.g. HP

Model : Model Number e.g. VXPC126

Price : Price of computer e.g.40258.99

i)Write a user defined function CreatePC() to input data for a record and append in

Computers.dat .

ii. Write a function FindPCs(Price) in Python which accepts the Price as parameter and

display only those computer records from Computers.dat which are having less than or

equal to given price.

Multiple Choice Questions

1. Which of the following statements is true?

a. load method of pickle module gives error if EOF is reached

b. load method of pickle module returns an empty string is EOF is reached

c. load method of pickle module returns -1 if EOF is reached

d. None of the above

2. Shylesh is writing python code to append a new record to a binary file ‘salary.dat’

that is storing list objects containing [empid, empname, salary]. Consider the

following code written by him.

import pickle

f = open(‘salary.dat’, ‘ab’)

id = input(“Enter employee id : ”)

name = input(“Enter name of employee: ”)

sal = float(input(“Enter salary :”))

record = ___________ #Blank 1

pickle.dump(record,f)

f.close()

Identify the missing part of Blank 1.

a. [id,name,sal]

b. id, name, sal

c. [empid, empname, salary]

d. empid, empname, salary

3. Which is the valid syntax to write an object onto a binary file opened in the write

mode?

a. pickle.dump(<object to be written>, <file handle of open file>)

b. pickle.dump(<file handle of open file>, <object to be written>)

c. dump.pickle(<object>, <file handle>)

d. None of the above

4. What is the binary file mode associated with “ file must exist, otherwise error will

be raised and reading and writing can take place”.

a. wb+

b. w+

c. rb

d. rb+

5. Rahul is trying to write a tuple t = (10,20,30,40,50) on a binary file

notebook.bin. Consider the following code written by him.

import pickle #statement 1

t = (10,20,30,40,50) #statement 2

myfile = open("notebook.bin",'w') #statement 3

pickle.dump(t, myfile) #statement 4

myfile.close()

Which of the following statement contains an error?

a. Statement 1

b. Statement 2

c. Statement 3

d. Statement 4

6. A binary file “salary.dat” has structure [employee id, employee name, salary].

What the following code will display:

def records():

num=0

fobj=open("data.dat","rb")

try:

print("Emp id\tEmp Name\tEmp Sal")

while True:

rec=pickle.load(fobj)

if rec[2]< 20000:

print(rec[0],"\t\t",rec[1],"\t\t",rec[2])

except:

fobj.close()

records()

a. Display the details of those employee whose salary is above 20000.

b. Display the details of all the employees.

c. Display the salaries of all the employees.

d. Display the details of those employees whose salary is less than 20000.

7. In which file, no delimiters are used for line and no translations occur?

(a) Text file

(b) Binary file

(c) csv file

(d) None of the above

8. Choose the file mode used to write data into binary file.

(a) rb

(b) wb

(c) r+

(d) w+

9. Which of the following function is used to read data from a binary file?

(a) write

(b) load

(c) dump

(d) scan

10. Dima is trying to read a list l1 from a binary file ‘num’. Consider the following

code written by her.

import pickle

f1 = open("num",'rb')

l1=__________________#Statement 1

print(l1)

f1.close()

Identify the missing code in Statement 1.

(a) pickle.load(f1)

(b) pickle.load(l1,f1)

(c) pickle.read(f1)

(d) pickle.dump(l1,f1)

Answers:

a.load method of pickle module gives error if EOF is reached

a.[id,name,sal]

a. pickle.dump(<object to be written>, <file handle of open file>)

d. rb+

c. Statement 3

d.Display the details of those employees whose salary is less than 20000.

(b) Binary file

(b) wb

(b) load

(a) pickle.load(f1)

CASE STUDY QUESTIONS

Amit Kumar of class 12 is writing a program to store roman numbers and find their

equivalents using a dictionary. He has written the following code. As a programmer,

help him to successfully execute the given task.

import __________ #Line 1

numericals = {1: ‘I’, 4 : ‘IV’, 5: ‘V’ , 9: ‘IX’, 10:’X’, 40:’XL’,50:’L’, 90:’XC’,

100:’C’,400:’CD’,500:’D’,900:’CM’,1000:’M’}

file1 = open(“roman.log”,”_______”) #Line 2

pickle.dump(numerals,file1)

file1.close()

file2 = open(“roman.log”,’________”) #Line 3

num = pickle.load(file2)

file2.__________ #Line 4

n = 0

while n!=-1:

print(“Enter 1,4,5,9,10,40,50,90,100,400,500,900,1000:”)

print(“or enter -1 to exit”)

n = int(input(“Enter numbers”))

if n!= -1:

print(“Equivalent roman number of this numeral is:”,num[n])

else:

print(“Thank You”)

(a) Name the module he should import in Line 1.

(b) In which mode, Amit should open the file to add data into the file in Line #2

(c) Fill in the blank in Line 3 to read the data from a binary file.

(d) Fill in the blank in Line 4 to close the file.

(e) Write the output he will obtain while input is 100.

Answers:

(a) pickle

(b) wb

(c) rb

(d) file2.close()

(e) C

LONG ANSWER QUESTIONS

1. A binary file “emp.dat” has structure [EID, Ename, designation, salary].

I.Write a user defined function CreateEmp() to input data for a record and add to emp.dat.

II.Write a function display() in Python to display the detail of all employees.

Answer:

I.

import pickle

def CreateEmp():

f1=open("emp.dat",'wb')

eid=input("Enter E. Id")

ename=input("Enter Name")

designation=input("Enter Designation")

salary=int(input("Enter Salary"))

l=[eid,ename,designation,salary]

pickle.dump(l,f1)

f1.close()

II.

import pickle

def display():

f2=open("emp.dat","rb")

while True:

try:

rec=pickle.load(f2)

print(rec['eid'],rec['ename'],rec['designation'],rec['salary'])

except EOFError:

break

f2.close()

2. A binary file “emp.DAT” has structure [EID, Ename, designation,salary].

I.Write a function to write more items in emp.dat.

II.Write a function Show() in Python that would read detail of employee from file “emp.dat” and display the details of those employee whose designation is “Manager”.

I)

import pickle

def createemp():

f1=open("emp.dat",'ab')

eid=input("Enter E. Id")

ename=input("Enter Name")

designation=input("Enter Designation")

salary=int(input("Enter Salary"))

l=[eid,ename,designation,salary]

pickle.dump(l,f1)

f1.close()

II) def Show():

f2=open("emp.dat","rb")

while True:

try:

rec=pickle.load(f2)

if (rec['designation']=='Manager'):

print(rec['eid'],rec['ename'],

rec['designation'],rec['salary'])

except EOFError:

break

f2.close()

3. A binary file “employee.dat” has structure [ empId, empName , Dept, Salary].

(i) Write a user defined function addData() to input data for a record and add tp

employee.dat

(ii) Write a function checkSalary(empName) in Python which accepts the empName as

parameter and return the salary of particular employee by the given employee name stored

in the file employee.dat

(i)

import pickle

def addData():

fobj=open("employee.dat","ab")

empID=int(input("Enter Emp ID : "))

empName=input("Employee Name :")

Dept = input(“Department: “)

Salary = int(input("Monthly Salary : "))

rec=[ empId, empName , Dept, Salary]

pickle.dump(rec,fobj)

fobj.close()

(ii)

import pickle

def checkSalary(empName):

fobj=open("employee.dat","rb")

num = 0

try:

while True:

rec=pickle.load(fobj)

if Author==rec[3]:

num = num + 1

except:

fobj.close()

return num

4. A binary file “discovery.dat” has a structure

[scien_name,discovery,yearofDiscovery,yearofbirth]

Write a function display(scien_name) in python that accepts the name of a scientist as

scien_name and returns the discovery with the year of discovery.

import pickle

def display(scien_name):

fobj=open("Discovery.DAT","rb")

num = 0

try:

while True:

rec=pickle.load(fobj)

if rec[1] == scien_name:

print(rec[0],rec[1],rec[2],sep="\t")

num = num + 1

except:

fobj.close()

return num

CSV FILE

• A Comma Separated Values (CSV) file is a plain text file that contains the commaseparated

data.

• These files are often used for exchanging data between different applications.

• CSV files are usually created by programs that handle huge amounts of data. They

are used to export data from spreadsheets (ex:- excel file) and databases (Ex:- Oracle,

MySQL). It can be used to import data into a spreadsheet or a database.

CSV File Structure

## sample.csv file structure

Name, DOB, City

Ram, 12-Jul-2001, Delhi

Mohan, 23-Jan-2005, Delhi

Python CSV Module

CSV Module is available in Python Standard Library.

The CSV module contains classes that are used to read and write tabular form of

data into CSV format.

To work with CSV Files, programmer have to import CSV Module.

import csv

Methods of CSV Module :

writer( )

reader( )

Both the methods return an Object of writer or reader class. Writer Object again have two

methods – writerow( ) , writerows( ).

writer( ) Methods

This function returns a writer object which is used for converting the data given by the

user into delimited strings on the file object.

writer( ) Object Methods –

w_obj . writerow( <Sequence> ) : Write a Single Line

w_obj . writerows ( <Nested Sequence> ) : Write Multiple Lines

Example:-

## writerow()

import csv

row=['Nikhil', 'CEO', '2', '9.0']

f=open("myfile.csv", 'w')

w_obj = csv.writer(f)

w_obj.writerow(row)

f.close()

## writerows()

import csv

rows = [['Nikhil','CEO','2','9.0'],

['Sanchit','CEO','2','9.1']]

f=open("myfile.csv",'w')

w_obj = csv.writer(f)

w_obj.writerows(rows)

f.close()

reader( ) Methods

This function returns a reader object which will be used to iterate over lines of a given

CSV file.

r_obj = csv.reader(csvfile_obj)

To access each row, we have to iterate over this Object.

for i in r_obj:

print(i)

import csv

f=open("myfile.csv",'r')

r_obj = csv.reader(f)

for data in r_obj:

print(data)

f.close()

SAMPLE QUESTIONS:

1. Write a program to read entire data from file data.csv

import csv f=open("data.csv", 'r')

d=csv.reader(f)

for row in d:

print(row)

OUTPUT:

['Admno', 'Name', 'Class', 'Sec', 'Marks']

['1231', 'Amit', 'XII', 'A', '45']

['1224', 'Anil', 'XII', 'B', '49']

['1765', 'Suman', 'XI', 'A', '42']

['2132', 'Naman', 'XII', 'C', '38']

2.Write a program to add/insert records in file “data.csv”. Structure of a record is roll

number, name and class.

import csv

field = ["Roll no" , "Name" , "Class"]

f = open("data.csv" , 'w')

d=csv.writer(f)

d.writerow(field)

rn=int(input("Enter Roll number: "))

nm = input("Enter name: ")

cls = input("Enter Class: ")

rec=[rn,nm,cls]

d.writerow(rec)

f.close()

Multiple Choice Questions:

1. CSV stands for :

a. Comma Separated Values

b. Comma Separated Variables

c. Comma Stored Values

d. Comma Stored Variables

2. The separator character of CSV Files is called a

a. EOL

b. Delimiter

c. EOF

d. Default

3. The default delimiter for a CSV file is :

a. Semi colon

b. Colon

c. Comma

d. Hyphen

4. _____ module of Python provides the functionality to read and write tabular data

in CSV file.

a. pickle

b. csv

c. file

d. ccv

5. Which function is used to open a csv file ?

a. Open()

b. csv.open()

c. writer()

d. csv.writer()

6. Name the function to read from CSV file.

a. read()

b. csv.reader()

c. csv.read()

d. readline()

7. Which among the following is not a function of csv module?

a. reader()

b. read()

c. writer()

d. writerows()

8. In Python, default newline character is :

a. \f

b. \t

c. \n

d. \v

9. CSV module allows to write multiple rows using function.

a. writerows( )

b. writerow( )

c. writer( )

d. None of the above

10. The opening function of a csv file is similar to the opening of:

a. Binary file

b. Text File

c. Both of them

d. None of them

11. The _______argument of open function is to specify how Python handle the

newline characters in csv file

a. newline

b. line

c. mode

d. char

12. Which among the following is an iterable object ?

a. writer

b. file

c. reader

d. All of the above

13. To specify a different delimiter while writing into a csv file, argument is used

with writer object :

a. newline

b. separator

c. character

d. delimiter

14. Which mode opens the file for exclusive creation, which fails in the case where file

already exists

a. a

b. w

c. x

d. r

15. The file mode to open a CSV file for reading as well as writing is .

a. a+

b. w+

c. r+

d. All the above.

16. Identify the line number which may cause an error:

import csv #Line1

line=[[1,2,3],[4,5,6]]#Line 2

with open("sample.csv","w",newline="") as csvfile: #Line3

writer=csv.writer(csvfile,delimiter="|") #Line4

for line in writer: #Line5

writer.writerow(line)

a. Line1

b. Line2

c. Line 4

d. Line

17. The CSV files are files.

a. Plain text file

b. Binary

c. Data

d. Python

18. The writer() function has how many mandatory parameters?

a. 1

b. 2

c. 3

d. 4

19. Which of the following parameter needs to be added with open function to avoid

blank row followed by each record in the CSV file?

a. quotechar

b. quoting

c. newline

d. skiprow

20. Ajaikrishna wants to separate the values by a $ sign. Suggests him a pair of function

and parameter to use it.

a. open, quotechar

b. writer, quotechar

c. open, delimiter

d. writer, delimiter

21. Tejalakshmi of Class 12 have written the below code . Observe and fill in the given

blanks so that it opens the file “data.csv” and read and print all the records.

I. What must be filled in line 1?

a. Open(“data.csv”,”r”)

b. open(“data.csv”)

c. “data.csv”

d. File

II. What must be filled in Line 2?

a. csv.reader()

b. csv.read()

c. csv.write()

d. csv.writer()

III. What must be filled in line 3?

a. data.csv

b. f

c. r

d. None

IV. What must be filled in line 4?

a. data

b. f

c. “File”

d. row

V. What is the default data type of data read from this file?

a. List

b. String

c. Tuple

d. Integer

22. Sudev, a student of class 12th, is learning CSV File Module in Python. During

examination, he has been assigned an incomplete python code to create a CSV file

‘customer.csv’ .Help him in completing the code which creates the desired CSV file.

I. Identify suitable code for the blank space in line marked as Statement-1.

a) include

b) add

c) Import

d) import

II. Identify the missing code for the blank space in line marked as Statement-2.

a) Customer

b) reader

c) csvwriter

d) writer

III. Identify the argument name for the blank space in line marked as Statement-3?

a) Row

b) Rec

c) row

d) rec

IV. Identify the missing file name for the blank space in line marked as Statement-4?

a) customer

b) customer.csv

c) customer.txt

d) customer.dat

V .Identify the object name for the blank space in line marked as Statement-5?

a) i

b) Rec

c) row

d) rec

23. Daya of class 12 is writing a program to create a CSV file “empdata.csv” with empid,

name & mobile number. Also to search a particular empid and display its record details.

He has written the following code. As a programmer, help him to successfully execute the

given task.

Choose the module he should import in Line 1.

a) math

b) pickle

c) csv

d) random

II. Choose a code to write the column heading from fields list in Line2.

a) writerows(fields)

b) writerow(field)

c) writerow(fields)

d) writerows(fields)

III. Choose a code to write the row from rows list in Line3.

a) writerows(row)

b) writerow(row)

c) writerow(rows)

d) write_row(row)

IV. Choose a code for line 4 to read the data from a csv file.

a) csv.reader(f)

b) csv.read(f) d) pickle.load(f) e) f.read()

V. Choose the correct variable (list value) to check “emplid” in Line5

a) Row[0]

b) Rec[0]

c) row[0]

d) rec[0]

24.Viraj is making a software on “Countries and their Capitals” in which various records

are to be stored/retrieved in “CAPITAL.CSV” data file. It consists of few records of

Countries and their Capitals. He has written the following code in python. As a

programmer, you have to help him to successfully execute the program.

I. Choose the Name of the function in Statement-1.

a) AddNewRec

b) Addnew

c) Addrec

d) AddNewRec()

II. Choose the file mode to be passed to add new records in Statement-2.

a) w

b) r

c) w+

d) a

III. Identify the correct variables in Statement-3 to store data to the file.

a) country,capital

b) Country,Capital

c) Coun,Cap

d) [Country,Capital]

IV. Choose the correct option for Statement-4 to read the data from a csv file.

a) Reader()

b) reader()

c) read

d) reader

V. Choose the output which will come after executing Statement-5.

a) ‘INDIA NEW DELHI’ ‘CHINA BEIJING’

b) ‘CHINA’ ‘BEIJING’

c) INDIA NEW DELHI

d)None of the above

25. Rinsha of class 12 is writing a program to create a CSV file “user.csv” which will

contain user name and password for some entries. She has written the following code.

As a programmer, help her to successfully execute the given task.

I. Name the module she should import in Line 1.

a. CSV

b. csv

c. math

d. File

II. In which mode, Rinsha should open the file to add data into the file.

a. r

b. a

c. w

d. w+

III. Fill in the blank in Line 3 to read the data from a csv file.

a. writer()

b. reader()

c. write()

d. read()

IV. Fill in the blank in Line 4 to close the file.

a. End()

b. Close()

c. close()

d. end()

26. Consider the following csv file and the code fragment associated with the following

csv file :

I.What will be the output printed by the above code?

a. SLNO12345

b. SLNO

c. The entire content

d. Error

II. What will be the output printed by the above code if the break is replaced with

continue?

a. SLNO12345

b. SLNO

c. The entire content

d. Error

III. What will occur if the file stud.csv is not existing in the mentioned path?

a. It will create a new one

b. It will create an error

c. None of the above

d. It will cause a system reboot

IV. Which statement in the above code will help to move to the next record?

a. fobj.next()

b. next(fobj)

c. fobj.move()

d. fobj.forward()

27. Sai Krishna has created the following csv file named item.csv:

He has written the following program for managing the file. Help him to find the

answers for the following questions.

I. What will be printed by Line1?

a. All the records

b. ITEMNO, NAME, PRICE c.item.csv

d. None of the above

II. What will be printed by Line2?

a. 101,PENCIL,5

b. ITEMNO, NAME, PRICE c.102,PEN,10

d. 103,NOTEBOOK,156

III. What will be printed by Line3?

a. 103,NOTEBOOK,15

b. Line 3 will not be executed

c. Line 3 will be executed , but nothing will be printed

d. 102,PEN,10

IV. What will be printed by Line4?

a. 101,PENCIL,5

b. ITEMNO, NAME, PRICE

c. 102,PEN,10

d. 103,NOTEBOOK,15

V. What must be written in Line 5?

a. F.close()

b. f.close()

c. fobj.close()

d. csvfile.close()



Comments

Popular posts from this blog

Class XII CSC Question Paper Template for 2023-24

Exception Handling Notes and Solved Question and Answers