Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

CH 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

Files – Text Files

A text file stores information in the form of a stream of ASCII or Unicode characters.
In text files, each line of text is terminated, (delimited) with a special character known
as EOL (End of Line) character. In Python, by default, this EOL character is the
newline character ('\n') or carriage-return, newline combination ('\r\n').
The text files can be of following types:
1. Regular Text files: These are the text files which store the text in the same
form as typed. Here the newline character ends a line and the text translations
take place. These files have a file extension as .txt.
2. Delimited Text files: In these text files, a specific character is stored to
separate the values, i.e., after each value, e.g., a tab or a comma after every
value.
a. When the comma is used to separate the values stored, these are called
CSV files (Comma Separated Values files). These files take the extension
as .csv.
Files – Binary Files
A binary file stores the information in the form of a stream of bytes. A binary file
contains information in the same format in which the information is held in memory,
i.e., the file content that is returned to you is raw (with no translation or no specific
encoding). As a result, binary files are faster and easier for a program to read and
write than are text files. As long as the file doesn't need to be read by people or need
to be ported to a different type of system, binary files are the best way to store
program information.

File Object: A file object is a reference to a file on disk. It opens the file and makes
it available for a number of different tasks.
Absolute Vs Relative path:
An absolute path is defined as specifying the location of a file or directory from the
root directory. In other words, we can say that an absolute path is a complete path
from start of actual file system from / directory.
Relative path is defined as the path related to the present working directly.

File Modes: A file mode govern the type of operations (read/write/append)


possible in the opened file.
Sr.No. Modes & Description

r: Opens a file for reading only. The file pointer is placed at the beginning
1
of the file. This is the default mode.

r+: Opens a file for both reading and writing. The file pointer placed at
2
the beginning of the file.

w: Opens a file for writing only. Overwrites the file if the file exists. If the
3
file does not exist, creates a new file for writing.

w+: Opens a file for both writing and reading. Overwrites the existing file
4 if the file exists. If the file does not exist, creates a new file for reading
and writing.

a: Opens a file for appending. The file pointer is at the end of the file if
5 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.

59
a+: Opens a file for both appending and reading. The file pointer is at the
6 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.

File Read Methods:


Sr.No. Methods & Description

Filehandle.read([n]): reads and return n byres, if n is not specified it


1
reads entire file.

Filehandle.readline([n]): reads a line of input. If n is specified reads at


2 most n bytes. Read bytes in the form of string ending with end of line
character of blank string if no more bytes are left for reading.

3 Filehandle.readlines(): reads all the lines and return them in a list.

File Write Methods:


Sr.No. Methods & Description

1 Filehandle.write(str): Write string str to file referenced by filehandle.

Filehandle.writelines(L): Write all strings in list L as lines to file


2
referenced by filehandle.

Opening text file:


open() function: The open() function is used to open a file in the following manner:
<file-objectname> = open(<filename>)
<file-objectname> = open(<filename>,<mode>)
By default the file open mode is read mode.

with statement: with statement will automatically close the file after the nested block
of code. It is guaranteed to close the file no matter how the nested block exits. Even
if an exception occurs with statement will handle it and close the file. It is used in the
following manner:
with open(<filename>,<filemode>) as <filehandle>:
<file manipulation statements>

Closing a text file: A close() function breaks the link of file-object and the file on
the disk. No tasks cab be performed after the file is closed. It is used in the following
way:
<file-handle>.close()

The tell() Function: The tell() function returns the current position of the file pointer
in a file. It is used as per the following syntax:

60
<file-object>.tell()

The seek() Function: the seek() function changes the position of the file pointer by
placing the file pointer at the specified position in the opened file. Its is used as per
the following syntax:
<file-object>.seek(offset[, mode])
offset: is a number specifying number of bytes.
mode: 0 – for beginning of the file – by default 0
1 – for current position of file pointer
2 – for end of the file

Questions – 1 Mark - MCQ

Q1. To open a file c:\ss.txt for appending data we use


a. file = open(‘c:\\ss.txt’,’a’)
b. file = open(r‘c:\ss.txt’,’a’)
c. file = open(‘c:\\ss.txt’,’w’)
d. both a and b

Q2. To read the next line of the file from the file object infi, we use
a. infi.read(all)
b. infi.read()
c. infi.readline()
d. infi.readlines()
Q3. Which function is used to ensure that the data in written in the file
immediately?
a. <filehandle>.write()
b. <filehandle>.writelines()
c. flush()
d. <filehandle>.close()
Q4. What is the datatype of the value returned by readlines() function?
a. Integer
b. String
c. List of strings
d. None of the above

Q5. What is the position of the cursor when the file is opened in append mode?
a. Start of file
b. End of file
c. At the 11th byte
d. Unknown

Q6. How to open a file such that close function is not needed to be called in order
to close the connection between file and python program?
a. Using open() method
b. Using read() method
c. Using with keyword
d. Using open with method

61
Q7. What is the full form of CSV?
a. Common segregated values
b. Comma separated values
c. Common separated values
d. None of the above

Q8. If a file is opened for writing


a. File must exist before opening
b. File will be created if does not exist
c. None of the above
d. Both a and b

Q9. If the cursor in the file is at the end of the file, then what will the read()
function return?
a. None
b. False
c. Exception
d. Empty string
Q10. Which is the value of mode parameter to set the offset of the cursor from the
end of the file?
a. 0
b. 1
c. 2
d. None of the above

Questions – 2 Marks – Short Answer


Q1. What is the difference between opening mode ‘a’ and ‘w’?

Q2. What is the purpose of flush() in file handling operations?

Q3. What is the advantage of opening file using with keyword?

Q4. Consider the following file ‘corona.txt’


O corona O corona
Jaldi se tum Go na
Social Distancing ka palan karona
Sabse 1 meter ki duri rakho na
Write the output of the following statement:
f = open(‘corona.txt’)
str1 = ____________ # to read first line
str2 = ____________ # to read next line of file
str3 = ____________ # to read remaining lines of the file

Q5. Consider the following file ‘corona.txt’


O corona O corona
Jaldi se tum Go na
Social Distancing ka palan karona
Sabse 1 meter ki duri rakho na
Complete the missing statement using fir loop to print all the lines of code:
62
f = open(‘corona.txt’)
for ____________:
print(____)

Q6. Given a file ‘data.txt’ write a function atoesidp() to display the file after
replacing ‘a’ with ‘e’.

Q7. What is the advantage of saving a file in text form and binary form?

Q8. What is the output of following code?


fh = open(‘main.txt’,’r’)
size = len(fh.read())
print(fh.read())

Q9. Write the output of the following program


f = open(‘data.txt’, ’w+’)
f.write(‘0123456789abcdef’)
f.write(‘xyz1234’)
f.seek(0)
print( f.read())
f.close()

Q10. If a file ‘f.txt’ contains data ‘Good’ and then what is the content of the file
f.txt then following program in run?
f = open(‘f.txt’, ‘w’)
f.write(‘Bye’)
Questions – 3 Marks – Long Answer

Q1. Differentiate between ‘r’ and ‘w’ file open modes and ‘w’ and ‘a’ file open mode.

Q2. Write a function stats() that accepts a filename and reports the files longest line.

Q3. A text file contains alphanumeric text (say an.txt). Write a program that reads
this text file and prints only the numbers or digits from the file.

Q4. Write a program to read a text file and display the count of lowercase and
uppercase letters in the file.

Q5. Write a method in python to read lines from a text file INDIA. TXT, to find and
display the Occurrence of the word "India".

Q6. Write a program that copies a text file "source.txt” onto "target.txt" barring the
starting with a "@" sign.

Q7. Take a sample text file and find the most commonly occurring word. Also, list
the frequencies of words in the text file.
Q8. Write a program to read a text file line by line and display each word separated
by a #.

Q9. Write a function remove_lowercase() that accepts two filenames, and copies all
the lines that do not start with a lowercase letter from the first file into the second.

Q10. Write a program to display all the records in a file along with line/record
number.
Questions – 5 Marks – Case Based Questions

Q1. Dhanush's teacher has given him the following text file (HigherEd. txt).

Higher education improves an individual' s quality of life.


Studies show that, compared to high school graduates, college graduates have
longer life spans, better access to health care, better dietary and health
practices, greater economic stability and security.
We must ensure that our whole population receives an education that will allow full
and continuing participation in this dynamic period of economic history.

And the following incomplete code:


def fileFunction1(______ ) #Fil1_line5
fin = ________ #Fi11_line6
print( _______(N1)) #Fi11_line7
_____________ #Fil1_line8
print( _______(N2)) #Fil1_line9
#__main__
N1 = __________ #Fill_Line1
N2 = __________ #fill_Line2
Filename = _________ #Fill_Line3
fileFunction1 (Filename, N1, N2) #Line4
66
Help Dhanush to complete his work as per the following instructions:
a. Add code to blank lines Fill_Linel and Fill_Line2 so that two integer numbers
are read into variables N1 and N2.
Also, complete Fill_Line3 so that the function call below it makes sense, which is
sending 3 arguments : filename, and two numbers N1 and N2.
b. As per the function call, complete the function header in Fill _Line5.
c. Complete Fill _Line6 so that the text file is opened for reading in the file object
fin.
d. Complete Fill_Line7 and Fill_Line9 so that the passed number of characters are
read from the file and printed.
e. Complete Fill_ Line8 so that the characters till the end of the line from the
current position of the file pointer are read but not printed.

Q2. SHRUTHI has to complete her file-based assignment by tonight. She has been
given the following text file (Education.txt):

Higher education improves quality of life.


College graduates have longer life spans.
Education is birthright.
Shruthi has also received the following incomplete code.

def fileFunction1 (____,____) #Fill_Line5


fi = ___(fname,___) #Fill_Line6
fi._______ #Fill_Line7
fi._______ #Fill_Line8
fi.close()
print("Done")

def fileFunction2(fname, N1, N2):


fi = open(fname)
print(fi.read(N1))
fi.readline()
print( fi.read(N2) )
a = fi.readlines ()
print(a)
N1 = 16 #Line1
N2 = 22 #Line2
String = "India strengthening" #Line3
fileFunction1( ____,____) #Fill_Line4
fileFunction2 ( 'Education.txt', N1, N2)
Help her to complete her assignment as per the following instructions.
a. Complete Fill_Line4 so that the function call to FileFunction1() passes two
arguments: First as the filename and the second as the string given in Line 3.
b. Complete Fill_Line5 so that the function header is as per its function call.
c. Complete Fill_Line6 so that the file is opened in a mode that will allow it to
write the string at the end of the file without deleting anything from the file.
d. Complete Fill_Line7 and FilI_Line8 so that the passed string is written on to the
file, followed by a newline character.
e. What will be the output produced by the complete code?
Binary files store data in the binary format (0’s and 1’s) which is understandable by
the machine. So when we open the binary file in our machine, it decodes the data
and displays in a human-readable format.

Binary File Modes: File mode governs the type of operations read/write/append
possible in the opened file. It refers to how the file will be used once its opened.
File Mode Description
rb Read Only: Opens existing file for read operation
wb Write Only: Opens file for write operation. If file does not exist, file is
created. If file exists, it overwrites data.
ab Append: Opens file in write mode. If file exist, data will be appended
at the end.
rb+ Read and Write: File should exist, Both read and write operations can
be performed.
wb+ Write and Read: File created if not exist, If file exist, file is truncated.
ab+ Write and Read: File created if does not exist, If file exist data is
truncated.

Write data to a Binary File:

Pickle is a special python package that is used to generate data in binary format.
Pickle comes with few methods like dump( ) to write data in binary format.
Example:
import pickle
list =[ ] # empty list
while True:
roll = input("Enter student Roll No:")
sname = input("Enter student Name :")
student = {"roll":roll,"name":sname} # create a dictionary
list.append(student) # add the dictionary as an element
68
in the list
choice= input("Want to add more record(y/n) :")
if(choice=='n'):
break
file = open("student.dat","wb") # open file in binary and write
mode pickle.dump(list, file)
file.close( )

OUTPUT:
Enter student Roll No:1201
Enter student Name :Anil
Want to add more record(y/n) :y
Enter student Roll No:1202
Enter student Name :Sunil
Want to add more record(y/n) :n

Read data from a Binary File:

To read the data from a binary file, we have to use load( ) function of pickle
module.

Example:
import pickle file = open("student.dat", "rb")
list = pickle.load(file) print(list)
file.close( )
OUTPUT:
[{'roll': '1201', 'name': 'Anil'}, {'roll': '1202', 'name': 'Sunil'}]

Update a record in Binary File:

Locate the record to be updated by searching for it.


Make changes in the loaded record in memory
Write back onto the file at the exact location of record.
import pickle
roll = input('Enter roll number whose name you want to update in binary file :')
file = open("student.dat", "rb+")
list = pickle.load(file)
found = 0
lst = [ ]
for x in list:
if roll in x['roll']:
found = 1
x['name'] = input('Enter new name: ')
lst.append(x)
if found == 1:
file.seek(0)
pickle.dump(lst, file)
print("Record Updated")
else: print('roll number does not exist')
file.close( )
OUTPUT:
Enter roll number whose name you want to update in binary file :1202
Enter new name: Harish
69
Record Updated

Delete a record from binary file:


import pickle
roll = input('Enter roll number whose record you want to delete:')
file = open("student.dat", "rb+")
list = pickle.load(file)
found = 0
lst = []
for x in list:
if roll not in x['roll']:
lst.append(x)
else:
found = 1
if found == 1:
file.seek(0)
pickle.dump(lst, file)
print("Record Deleted ")
else:
print('Roll Number does not exist')
file.close( )
OUTPUT:
Enter roll number whose record you want to delete:1201
Record Deleted

Search a record in a binary file:


import pickle
roll = input('Enter roll number that you want to search in binary file :')
file = open("student.dat", "rb")
list = pickle.load(file)
file.close( )
for x in list:
if roll in x['roll']:
print("Name of student is:", x['name'])
break
else:
print("Record not found")
OUTPUT:
Enter roll number that you want to search in binary file :1202
Name of student is: Harish

tell( ) and seek( ) methods:


tell( ): It returns the current position of cursor in file.
Example:
fout=open("story.txt","w")
fout.write("Welcome Python")
print(fout.tell( ))
fout.close( )

Output:
15

seek(offset, reference_point) : Change the cursor position by bytes as specified by


70
the offset, from the reference point.
Example:
fout=open("story.txt","w")
fout.write("Welcome Python")
fout.seek(5)
print(fout.tell( ))
fout.close( )

Output:
5

Pickle Module: Python Pickle is used to serialize and deserialize a python object
structure. Any object on python can be pickled so that it can be saved on disk.

Pickling: Pickling is the process whereby a Python object hierarchy is converted into
a byte stream.

Unpickling: A byte stream is converted into object hierarchy.


To use the picking methods in a program, we have to import pickle module using
import keyword.

Example:
import pickle
In this module, we shall discuss to functions of pickle module, which are:
i. dump( ) : To store/write the object data to the file.
ii. load( ) : To read the object data from a file and returns the object data.
Syntax:
Write the object to the file:
pickle.dump(List_name, file-object )
Read the object from a file:
pickle.load(file-object)

1 Mark Questions
1. The process of converting byte stream back to the original structure is known as
a. Picklingb. b. Unpickling c. Packing d. Zipping

2. Which file mode is used to handle binary file for reading.


a. rb b. rw c. r d. w

3. Which of the following is not a correct statement for binary files?


a. Easy for carrying data into buffer
b. Much faster than other file systems
c. Characters translation is not required
d. Every line ends with new line character ‘\n’

4. Which one of the following is correct statement?


a. import – pickle b. pickle import c. import pickle d. All the above

5. Which of the following file mode opens a file for append or read a binary file and
moves the files pointer at the end of the file if the file already exist otherwise create
a new file?
a. a b. ab c. ab+ d. a+

71
6. Which of the following file mode opens a file for reading and writing both as well
as overwrite the existing file if the file exists otherwise creates a new file?
a. w b. wb+ c. wb d. rwb

7. Mr Sharma is working on a binary file and wants to write data from a list to a
binary file.
Consider list object as l1, binary file sharma_list.dat, and file object as f.
Which of the following can be the correct statement for him?
a. f = open(‘sum_list’,’wb’); pickle.dump(l1,f)
b. f = open(‘sum_list’,’rb’); l1=pickle.dump(f)
c. f = open(‘sum_list’,’wb’); pickle.load(l1,f)
d. f = open(‘sum_list’,’rb’); l1=pickle.load(f)

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

9. EOL Stands for :


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

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

2 Mark Questions

1. Write a program in python to write and read structure, dictionary to the binary
file.
2. BINARY file is unreadable and open and close through a function only so what are
the advantages of using binary file
3. Write a statement to open a binary file name sample.dat in read mode and the file
sample.dat is placed in a folder ( name school) existing in c drive
4. When do you think text files should be preferred over binary files?
5. Consider a binary file employee.dat containing details such as
empno:ename:salary (seperator ':') write a python function to display details of
those employees who are earning between 20000 and 30000(both values
inclusive)
6. Differentiate between pickle.load() and pickle.dump() methods with suitable
example.
7. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].Write
a user defined function CreateFile() to input data for a record and add to Book.dat
8. 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.
9. A binary file “Store.dat” has structure [ItemNo, Item_Name, Company, Price].
Write a function CountRec(Company) in Python which accepts the Company name
as parameter and count and return number of Items by the given Company are
stored in the binary file “Store.dat”.

72
10. A binary file “Store.dat” has structure [ItemNo, Item_Name, Company,
Price].
Write a function AddRecord(<List>) which accepts a List of the record [ItemNo,
Item_Name, Company, Price] and appends in the binary file “Store.Dat”

3 mark Questions
1. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].
i. Write a user defined function CreateFile() to input data for a record and add
to
“Book.dat” .
ii. Write a function CountRec(Author) in Python which accepts the Author name
as parameter and count and return number of books by the given Author are stored
in the binary file “Book.dat”

2. A binary file “SCHOOL.DAT” has structure [Roll_Num, Name, Percentage]


i) Write a function Count_Rec() in Python that would read contents of the file
“SCHOOL.DAT” and display the details of those students whose percentage is below
33 .
ii) Write a function Disp_Rec(alphabet) in Python that would read contents of the file
“SCHOOL.DAT” and display the details of those students whose name begin with the
alphabet as passed as parameter to the function.

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


PRICE]. Write a user defined function MakeFile( )to input data for a record and add
to Book.dat.

4. 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.

5. 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.

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


Write a function to display number of employees having Salary more than 20000.

7. A binary file named “EMP.dat” has some records of the structure [EmpNo,
EName, Post, Salary], Write a user-defined function named NewEmp() to input the
details of a new employee from the user and store it in EMP.dat.

8. Write a user-defined function named SumSalary(Post) that will accept an


argument the post of employees & read the contents of EMP.dat and calculate the
SUM of salary of all employees of that Post.

73
9. A binary file named “TEST.dat” has some records of the structure [TestId,
Subject, MaxMarks, ScoredMarks] Write a function in Python named
DisplayAvgMarks(Sub) that will accept a subject as an argument and read the
contents of TEST.dat.

10. Write a python program to search and display the record of the student from
a binary file “Student.dat” containing students records (Rollno, Name and Marks).
Roll number of the student to be searched will be entered by the user.

5 Mark Questions

1. A binary file “student.dat” has structure [rollno, name, marks]. i. Write a


user defined function insertRec() to input data for a student and add to student.dat.
ii. Write a function searchRollNo( r ) in Python which accepts the student’s rollno as
parameter and searches the record in the file “student.dat” and shows the details of
student i.e. rollno, name and marks (if found) otherwise shows the message as ‘No
record found’.

2. Write a python program to create binary file dvd.dat and write 10 records in
it Dvd id,dvd name,qty,price Display those dvd details whose dvd price more than
25.
Working with CSV Files: CSV (Comma Separated Values)

A csv file is a type of plain text file that uses specific structuring to arrange tabular
data. csv is a common format for data interchange as it is compact, simple and
general.
Each line of the file is one line of the table.
csv files have .csv as file extension.

Let us take a data.csv file which has the following contents:


Roll No., Name of student, stream, Marks
1, Anil, Arts, 426
2, Sujata, Science, 412

As you can see each row is a new line, and each column is separated with a comma.
This is an example of how a CSV file looks like.
To work with csv files, we have to import the csv module in our program.

Read a CSV file:


To read data from a CSV file, we have to use reader( ) function. The reader function
takes each row of the file and make a list of all columns.
CODE:
81
import csv
with open('C:\\data.csv','rt') as f:
data = csv.reader(f) #reader function to generate a reader object
for row in data:
print(row)

OUTPUT:
['Roll No.', 'Name of student', 'stream', 'Marks']
['1', 'Anil', 'Arts', '426']
['2', 'Sujata', 'Science', '412']

Write data to a CSV file:


When we want to write data in a CSV file you have to use writer( ) function.
To iterate the data over the rows (lines), you have to use the writerow( ) function.

CODE:
import csv
with open('C:\\data.csv', mode='a', newline='') as file:
writer = csv.writer(file, delimiter=',', quotechar='"' ) #write new record in file
writer.writerow(['3', 'Shivani', 'Commerce', '448'])
writer.writerow(['4', 'Devansh', 'Arts', '404'])

OUTPUT:
['Roll No.', 'Name of student', 'stream', 'Marks']
['1', 'Anil', 'Arts', '426']
['2', 'Sujata', 'Science', '412']
['3', 'Shivani', 'Commerce', '448']
['4', 'Devansh', 'Arts', '404']

When we shall open the file in notepad (Flat file) then the contents of the file will look
like this:
Roll No.,Name of student,stream,Marks
1,Anil,Arts,426
2,Sujata,Science,412
3,Shivani,Commerce,448

82
4,Devansh,Arts,404

For Practical Explanation


Program-1:-Write a program to perform read and write operation with .csv file.

CODE:
import csv
def readcsv():
with open('C:\\data.csv','rt')as f:
data = csv.reader(f) #reader function to generate a reader object
for row in data:
print(row)

def writecsv( ):
with open('C:\\data.csv', mode='a', newline='') as file:
writer = csv.writer(file, delimiter=',', quotechar='"') #write new record in file
writer.writerow(['4', 'Devansh', 'Arts', '404'])

print("Press-1 to Read Data and Press-2 to Write data: ")


a=int(input())
if a==1:
readcsv()
elif a==2:
writecsv()
else:
print("Invalid value")

OUTPUT:

Press-1 to Read Data and Press-2 to Write data: 1


['Roll No.', 'Name of student', 'stream', 'Marks']
['1', 'Anil', 'Arts', '426']
['2', 'Sujata', 'Science', '412']
['3', 'Shivani', 'Commerce', '448']
['4', 'Devansh', 'Arts', '404']

Program-2:- CreateaCSVfilebyenteringuser-
idandpassword,readandsearchthepasswordforgivenuser-id.
CODE:
83
import csv
with open("user_info.csv", "w") as obj:
fileobj = csv.writer(obj)
fileobj.writerow(["User Id", "password"])
while(True):
user_id = input("enter id: ")
password = input("enter password: ")
record = [user_id, password]
fileobj.writerow(record)
x = input("press Y/y to continue and N/n to terminate the program\n")
if x in "Nn":
break
elif x in "Yy":
continue
with open("user_info.csv", "r") as obj2:
fileobj2 = csv.reader(obj2)
given = input("enter the user id to be searched\n")
for i in fileobj2:
next(fileobj2)
# print(i,given)
if i[0] == given:
print(i[1])
break
OUTPUT:
enter id: cbse
enter password: 123
press Y/y to continue and N/n to terminate the program
y
enter id: computer_science
enter password: python
press Y/y to continue and N/n to terminate the program
n
enter the user id to be searched
cbse
123
>>>
Sample Questions & Answers

84
1. What does the acronym CSV stand for in its full form?
a. Common Separated Value
b. Comma System Value
c. Comma Separated Value
d. Common System Vault

2. What is the default delimiter of a CSV file


a. Tab
b. Comma
c. Semicolon
d. Space

3. In regards to separated value files such as .csv and .tsv, what is the delimiter?
a. Any character such as the comma (,) or tab (\t) that is used to separate
the row data
b. Anywhere the comma (,) character is used in the file
c. Delimiters are not used in separated value files
d. Any character such as the comma (,) or tab (\t) that is used to separate
the column data.

4. In separated value files such as .csv and .tsv, what does the first row in the file
typically contain?
a. The source of the data
b. The author of the table data
c. Notes about the table data
d. The column names of the data

5. Assume you have a file object my_data which has properly opened a separated
value file that uses the tab character (\t) as the delimiter.
What is the proper way to open the file using the Python csv module and assign it
to the variable csv_reader?
Assume that csv has already been imported.
a. csv_reader = csv.tab_reader(my_data)
b. csv_reader = csv.reader(my_data)
c. csv_reader = csv.reader(my_data, tab_delimited=True)
d. csv_reader = csv.reader(my_data, delimiter='\t')

6. When iterating over an object returned from csv.reader(), what is returned with
each iteration?
For example, given the following code block that assumes csv_reader is an
object
returned from csv.reader(), what would be printed to the console with each
iteration?
85
for item in csv_reader:
print(item)

a. The individual value data that is separated by the delimiter


b. The row data as a list
c. The column data as a list
d. The full line of the file as a string

7. Case study Question-

Neha is making software on “Items & their prices” in which various records are to be
stored/retrieved in STORE.CSV data file. It consists some records (Item & Price).
She has written the following code in python. As a programmer, you have to help her
to successfully execute the program.

import ___________ # Statement-1


def AddItem(Item, Price) ___ # Statement-2
f=open(“STORE.CSV”, ___ ) # Statement-3
fw=csv.writer(f)
fw.writerow([Item, Price])
____________ # Statement-4

def ShowRecord():
with open(“STORE.CSV”,”r”) as NI:
NewItem=csv._______ (NI) # Statement-5
for rec in NewItem:
print(rec[0], “#”, rec[1])

#main-code
AddItem(“Sugar”, 38.00)
AddItem(“Rice”, 48.50)
ShowRecord() # Statement-6

Q1. Which module should be imported in Statement-1.


A. pickle B. csv C. file D. text

Q2. Which file mode to be passed to add new record in Statement-3.


A. w+ B. w C. wb D. a

Q3. What should be written in Statement-4 to close the file?


A. close() B. fw.close() C. f.close() D. csv.close()

Q4. Which function to be used in Statement-5 to read the data from a csv
86
file.
A. read() B. readline() C. readlines() D. reader()

Q5. Output after executing Statement-6 will be -

A. (“Sugar”, “38.0”) B. Sugar 38.0


(“Rice”, “48.50”) Rice 48.0

C. Sugar, 38.0 D. Sugar # 38.0


Rice, 48.50 Rice # 48.50

You might also like