0% found this document useful (0 votes)
15 views36 pages

File Handling

The document outlines the CBSE syllabus for file handling in Python, covering the definition, types, and importance of files, including text, binary, and CSV files. It details how to open, read, write, and manipulate these files, along with the use of the 'pickle' module for binary files and the 'csv' module for CSV files. Additionally, it includes multiple-choice questions, fill-in-the-blanks, and true/false questions to assess understanding of file handling concepts.

Uploaded by

prafulla gouda
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)
15 views36 pages

File Handling

The document outlines the CBSE syllabus for file handling in Python, covering the definition, types, and importance of files, including text, binary, and CSV files. It details how to open, read, write, and manipulate these files, along with the use of the 'pickle' module for binary files and the 'csv' module for CSV files. Additionally, it includes multiple-choice questions, fill-in-the-blanks, and true/false questions to assess understanding of file handling concepts.

Uploaded by

prafulla gouda
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/ 36

FILE HANDLING

CBSE SYLLABUS
Files in Python
1. Introduction to Files

 Definition and importance of files


 Types of files: Text file, Binary file, CSV file
 File paths: Relative and Absolute paths

2. Text Files

 Opening a text file


 Text file open modes: r, r+, w, w+, a, a+
 Closing a text file
 Opening a file using with clause
 Writing/Appending data to a text file using write() and writelines()
 Reading from a text file using read(), readline(), and readlines()
 File handling methods: seek() and tell()
 Manipulation of data in a text file

3. Binary Files

 Basic operations on a binary file


 Opening a binary file using file open modes: rb, rb+, wb, wb+, ab, ab+
 Closing a binary file
 Importing the pickle module
 Writing and reading binary files using dump() and load() methods
 Performing operations: Read, Write/Create, Search, Append, and Update in a binary file

4. CSV Files

 Importing the csv module


 Opening and closing a CSV file
 Writing data into a CSV file using writer() and DictWriter()
 Reading data from a CSV file using reader() and DictReader()

writer(),writerow(),writerows() and read from a csv file using reader()

THEORY

Introduction to Files in Python


A file is a container that stores data permanently. Python provides file handling to read and write
data from files. Files can be categorized into three types:
1. Text Files (stores human-readable data in UTF-8 encoding)
2. Binary Files (stores non-text data like images, audio, video, and serialized objects)
3. CSV Files (Comma-Separated Values, used for tabular data)

Page 1 of 36
File Paths
 Absolute Path: Full path from the root directory (e.g., C:/Users/Desktop/file.txt)
 Relative Path: Path relative to the current working directory (e.g., data/file.txt)

Text Files in Python


Opening a Text File
file = open("example.txt", "r") # Opens file in read mode

Text File Open Modes


Mode Description
r Read (default)

r+ Read and Write

w Write (overwrites existing file)

w+ Read and Write (overwrites existing file)

a Append (adds to existing file)

a+ Read and Append

Closing a File
file.close()

Using with Clause


with open("example.txt", "r") as file:
content = file.read()

(Automatically closes the file after execution.)

Writing to a Text File


with open("example.txt", "w") as file:
file.write("Hello, World!\n")

Appending Data
with open("example.txt", "a") as file:
file.write("Appending new data.\n")

Reading from a File


with open("example.txt", "r") as file:
content = file.read() # Reads entire file
print(content)

Using readline() and readlines()


with open("example.txt", "r") as file:
print(file.readline()) # Reads one line
print(file.readlines()) # Reads all lines as a list

Page 2 of 36
Seek and Tell Methods
with open("example.txt", "r") as file:
file.seek(5) # Move cursor to 5th byte
print(file.read())
print(file.tell()) # Returns current cursor position

Binary Files in Python


Binary files store data in a format that is not human-readable.

Opening a Binary File


file = open("data.bin", "wb") # Write in binary mode
file.close()

Binary File Open Modes


Mode Description
rb Read binary
rb+ Read and write binary
wb Write binary (overwrites)
wb+ Read and write binary (overwrites)
ab Append binary
ab+ Read and append binary

Using the pickle Module


import pickle

# Writing an object to a binary file


data = {"Name": "John", "Age": 25}
with open("data.bin", "wb") as file:
pickle.dump(data, file) # Dumps data into binary file

# Reading an object from a binary file


with open("data.bin", "rb") as file:
loaded_data = pickle.load(file)
print(loaded_data)

Appending Data to a Binary File


with open("data.bin", "ab") as file:
pickle.dump({"City": "New York"}, file)

CSV Files in Python


CSV (Comma-Separated Values) files store tabular data in plain text.

Importing CSV Module


import csv

Opening and Closing a CSV File


with open("data.csv", "r") as file:
reader = csv.reader(file)

Page 3 of 36
for row in reader:
print(row)

Writing to a CSV File


with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "City"]) # Writing a single row
writer.writerows([["Alice", 30, "New York"], ["Bob", 25, "Chicago"]]) # Multiple rows

Reading from a CSV File


with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row) # Each row is read as a list

MCQ
Python File Handling MCQs with Answers
Question 1
Information stored on a storage device with a specific name is called a _________.
1. array
2. dictionary
3. file
4. tuple
Question 2
Which of the following formats of files can be created programmatically through Python to
store some data?
1. Data files
2. Text files
3. Video files
4. Binary files
Question 3
To open a file c:\ss.txt for appending data, we use
1. file = open("c:\ss.txt", "a")
2. file = open("c:\ss.txt", "rw")
3. file = open(r"c:\ss.txt", "a")
4. file = open(file = "c:\ss.txt", "w")
5. file = open(file = "c:\ss.txt", "w")
6. file = open("c:\res.txt")
Question 4
To read the next line of the file from a file object infi, we use
1. infi.read(all)
2. infi.read()
3. infi.readline()
4. infi.readlines()
Question 5
To read the remaining lines of the file from a file object infi, we use
1. infi.read(all)
2. infi.read()
3. infi.readline()
4. infi.readlines()
Question 6
The readlines() method returns
1. str

Page 4 of 36
2. a list of lines
3. a list of single characters
4. a list of integers
Question 7
Which of the following mode will refer to binary data?
1. r
2. w
3. o
4. b
Question 8
Which of the following statement is not correct?
1. We can write content into a text file opened using 'w' mode.
2. We can write content into a text file opened using 'w+' mode.
3. We can write content into a text file opened using 'r' mode.
4. We can write content into a text file opened using 'r+' mode.
Question 9
Which of the following option is the correct Python statement to read and display the first 10
characters of a text file "Notes.txt"?
1. F = open('Notes.txt') ; print(F.load(10))
2. F = open('Notes.txt') ; print(F.dump(10))
3. F = open('Notes.txt') ; print(F.read(10))
4. F = open('Notes.txt') ; print(F.write(10))
Question 10
Which of the following is not a correct Python statement to open a text file "Notes.txt" to write
content into it?
1. F = open('Notes.txt', 'w')
2. F = open('Notes.txt', 'a')
3. F = open('Notes.txt', 'A')
4. F = open('Notes.txt', 'w+')

Question 11
Which function is used to read all the characters ?
1. read()
2. readcharacters()
3. readall()
4. readchar()

Question 12
Which function is used to read a single line from file ?
1. readline()
2. readlines()
3. readstatement()
4. readfullline()

Question 13
Which function is used to write all the characters ?
1. write()
2. writecharacters()
3. writeall()
4. writechar()

Question 14
Which function is used to write a list of strings in a file ?

Page 5 of 36
1. writeline()
2. writelines()
3. writestatement()
4. writefullline()

Question 15
Which of the following represents mode of both writing and reading in binary format in file. ?
1. wb+
2. w
3. wb
4. w+
Question 16
Which of the following is not a valid mode to open a file ?
1. ab
2. rw
3. r+
4. w+

Question 17
Which of the following mode in file opening statement results or generates an error if the file does
not exist ?
1. a+
2. r+
3. w+
4. None of these

Question 18
Which of the following command is used to open a file "c:\pat.txt" in read-mode only ?
1. fin = open("c:\pat.txt", "r")
2. fin = open("c:\\pat.txt", "r")
3. fin = open(file = "c:\pat.txt", "r+")
4. fin = open(file = "c:\\pat.txt", "r+")

Question 19
Which of the following statements are true regarding the opening modes of a file ?
1. When you open a file for reading, if the file does not exist, an error occurs.
2. When you open a file for writing, if the file does not exist, an error occurs.
3. When you open a file for reading, if the file does not exist, the program will open an empty file.
4. When you open a file for writing, if the file does not exist, a new file is created.
5. When you open a file for writing, if the file exists, the existing file is overwritten with the
new file.

Question 20
Which of the following command is used to open a file "c:\pat.txt" for writing in binary format
only ?
1. fout = open("c:\pat.txt", "w")
2. fout = open("c:\\pat.txt", "wb")
3. fout = open("c:\pat.txt", "w+")
4. fout = open("c:\\pat.txt", "wb+")
Question 21

Page 6 of 36
Which of the following command is used to open a file "c:\pat.txt" for writing as well as reading
in binary format only ?
1. fout = open("c:\pat.txt", "w")
2. fout = open("c:\\pat.txt", "wb")
3. fout = open("c:\pat.txt", "w+")
4. fout = open("c:\\pat.txt", "wb+")

Question 22
Which of the following functions do you use to write data in the binary format ?
1. write()
2. output()
3. dump()
4. send()

Question 23
Which of the following option is the correct usage for the tell() of a file object ?
1. It places the file pointer at a desired offset in a file.
2. It returns the entire content of a file.
3. It returns the byte position of the file pointer as an integer.
4. It tells the details about the file.

Question 24
Which of the following statement is incorrect in the context of pickled binary files ?
1. The csv module is used for reading and writing objects in binary files.
2. The pickle module is used for reading and writing objects in binary files.
3. The load() of the pickle module is used to read objects.
4. The dump() of the pickle module is used to write objects.

Question 25
What is the significance of the seek() method ?
1. It seeks the absolute path of the file.
2. It tells the current byte position of the file pointer within the file.
3. It places the file pointer at a desired offset within the file.
4. It seeks the entire content of the file.

Question 26
The correct syntax of seek() is :
1. file_object.seek(offset[, reference_point])
2. seek(offset[, reference_point])
3. seek(offset, file_object)
4. seek.file_object(offset)

Fill in the Blanks


Question 1
The default file-open mode is read mode.
Question 2
A file mode governs the type of operations (e.g., read/write/append) possible in the opened file.
Question 3
The two types of data files can be text files and binary files.

Page 7 of 36
Question 4
The r+ file mode will open a file for read and write purpose.
Question 5
The w+ or a+ file mode will open a file for write and read purpose.
Question 6
To close an open file, close() method is used.
Question 7
To read all the file contents in the form of a list, readlines() method is used.
Question 8
To write a list in a file, writelines() method may be used.
Question 9
To force Python to write the contents of the file buffer onto a storage file, flush() method may be
used.
Question 10
To read and write into binary files, pickle module of Python is used.
Question 11
The dump() method of the pickle module writes data into a binary file.
Question 12
The load() method of the pickle module reads data from a binary file.
Question 13
The conversion of an object hierarchy into a byte stream is called serialization (or pickling).
Question 14
The character that separates the values in CSV files is called the delimiter.
Question 15
The default delimiter of CSV files is comma (,).
Question 16
The CSV files are actually text files.
Question 17
We can suppress EOL translation in a text file by giving newline='' argument in open().
Question 18
The file mode to open a binary file for reading as well as writing is rb+.
Question 19
The file mode to open a binary file for writing as well as reading is wb+.
Question 20
The file mode to open a CSV file for reading as well as writing is r+.
Question 21
The file mode to open a CSV file for appending as well as reading is a+.
Question 22
To specify a different delimiter while writing into a CSV file, delimiter argument is used with
csv.writer().

True/False Questions
Here are the questions with correct answers:
Question 1
When you open a file for reading, if the file does not exist, an error occurs.
True
Question 2
When you open a file for writing, if the file does not exist, an error occurs.
False (A new file is created if it does not exist.)
Question 3
When you open a file for writing, if the file exists, the existing file is overwritten with the new

Page 8 of 36
file.
True
Question 4
The absolute paths are from the topmost level of the directory structure.
True
Question 5
The relative paths are relative to the current working directory.
True
Question 6
The relative path for a file always remains the same even after changing the directory.
False (The relative path depends on the current working directory.)
Question 7
The types of operations that can be carried out on a file depend upon the file mode a file is
opened in.
True
Question 8
If no path is given with a file name in the open(), then the file must exist in the current directory.
True
Question 9
Functions readline() and readlines() are essentially the same.
False (readline() reads one line at a time, while readlines() reads all lines into a list.)
Question 10
Python automatically flushes the file buffers before closing a file with close() function.
True
Question 11
When you open a file for writing, if the file does not exist, a new file is created.
True
Question 12
When you open a file for appending, if the file exists, the existing file is overwritten with the
new file.
False (Appending adds new content at the end without overwriting the existing file.)
Question 13
Conversion of an object hierarchy into a byte stream is called Serialization.
True
Question 14
Serialization process is also called pickling.
True
Question 15
The load() function of the pickle module performs pickling.
False (load() performs unpickling, while dump() performs pickling.)
Question 16
The dump() function of the pickle module performs unpickling.
False (dump() performs pickling, while load() performs unpickling.)
Question 17
The CSV files can only take commas as delimiters.
False (CSV files can use different delimiters like semicolon ;, tab \t, or space, specified using the
delimiter argument.)
Question 18
The CSV files are text files.
True

Page 9 of 36
Assertions and Reasons

Question 1
Assertion: Python is said to have broadly two types of files - binary and text files, even when
there are CSV and TSV files also.
Reason: The CSV and TSV are types of delimited text files only where the delimiters are
comma and tab respectively.

Answer:
(a) Both the statements: assertion-reason are true, and the reason provided is the right
explanation for the assertion statement.

Question 2
Assertion: The file modes "r", "w", "a" work with text files, CSV files, and TSV files alike.
Reason: The CSV and TSV are types of delimited text files only.

Answer:
(a) Both the statements: assertion-reason are true, and the reason provided is the right
explanation for the assertion statement.

Question 3
Assertion: The file modes "r", "w", "a" also reveal the type of file these are being used with.
Reason: The binary file modes have a 'b' suffix with regular file modes.

Answer:
(c) The assertion statement is true, but the reason is incorrect.

Question 4Assertion: 'Pickling' is the process whereby a Python object hierarchy is


converted into a byte-stream.
Reason: A binary file works with byte-streams.

Answer:
(b) Both the statements: assertion-reason are true, but the reason which is provided is
not correct and does not apply to the assertion statement.

Question 5
Assertion: 'Pickling' is the process whereby a Python object hierarchy is converted into a
byte-stream.

Page 10 of 36
Reason: Pickling process is used to work with binary files as a binary file works with byte-
streams.

Answer:
(a) Both the statements: assertion-reason are true, and the reason provided is the right
explanation for the assertion statement.

Question 6
Assertion: Every open file maintains a file-pointer and keeps track of its position after every
operation.
Reason: Every read and write operation takes place at the current position of the file pointer.

Answer:
(a) Both the statements: assertion-reason are true, and the reason provided is the right
explanation for the assertion statement.

Question 7
Assertion: CSV (Comma Separated Values) is a file format for data storage that looks like a
text file.
Reason: The information is organized with one record on each line, and each field is
separated by a comma.

Answer:
(a) Both the statements: assertion-reason are true, and the reason provided is the right
explanation for the assertion statement.

Text File
1. Write a function in Python to count the number of lines in a text file ‘Country.txt’ that start with
the alphabet ‘W’ or ‘H’.

Answer –
def COUNTLINES():
file = open('STORY.TXT', 'r') # Open the file in read mode
lines = file.readlines() # Read all lines into a list
count = 0 # Initialize counter

for w in lines:
if w.strip(): # Check if line is not empty
if w[0] == "A" or w[0] == "a": # Check if the first character is 'A' or 'a'
count += 1

print("Total lines:", count) # Print the count


file.close() # Close the file

2. Write a user-defined function countwords() to display the total number of words present in the file
“Quotes.Txt”.

Page 11 of 36
Answer-
def countwords():
with open("Mydata", "r") as s: # Open the file in read mode
f = s.read() # Read the entire content of the file
z = f.split() # Split the text into words
count = len(z) # Count the number of words
print("Total number of words:", count) # Print the count

3. Write a function COUNT_AND() in Python to read the text file “STORY.TXT” and count the
number of times “AND” occurs in the file (including AND/and/And in the counting).

Answer-
def count_my():
with open("DATA.TXT", "r") as f: # Open file in read mode
count = 0
x = f.read() # Read the entire content of the file
words = x.split() # Split text into words
for i in words:
if i.lower() == "my": # Case insensitive match
count += 1
print("The word 'my' occurs", count, "times.")

# Call the function


count_my()

4. Write a function DISPLAYWORDS() in Python to display the count of words starting with “t” or
“T” in a text file ‘STORY.TXT’.

Answer-
def COUNT_AND():
count = 0
file = open('STORY.TXT', 'r') # Open the file in read mode
line = file.read()
word = line.split()
for w in word:
if w[0] == 't' or w[0] == 'T': # Check if the word starts with 't' or 'T'
count = count + 1
print(count) # Print the total count

5. Write a function that counts and displays the number of 5-letter words in a text file “Sample.txt”.

Answer-
def count_words():
c=0
f = open("Sample.txt", "r") # Open the file in read mode
line = f.read()
word = line.split()
for w in word:
if len(w) == 5: # Check if the word length is 5

Page 12 of 36
c += 1
print(c) # Print the count of words with length 5
f.close() # Close the file

6. Write a function to display those lines which start with the letter “G” from the text file
“MyNotes.txt”.

Answer-
def count_lines():
c=0
f = open("MyNotes.txt", "r") # Open the file in read mode
line = f.readlines()
for w in line:
if w[0] == 'G': # Check if the line starts with 'G'
print(w)
f.close() # Close the file

7. Write a function in Python to read lines from the file “POEM.txt” and display all those words
which have two characters in them.

Answer-
def TwoCharWord():
f = open('poem.txt', 'r') # Open the file in read mode
count = 0
for line in f:
words = line.split()
for w in words:
if len(w) == 2: # Check if the word has exactly 2 characters
print(w, end=' ')
f.close() # Close the file

8. Write a function COUNT() in Python to read contents from the file “REPEATED.TXT” and count
and display the occurrence of the words “Catholic” or “mother”.

Answer-
def COUNT():
f = open('REPEATED.txt', 'r') # Open the file in read mode
count = 0
for line in f:
words = line.split()
for w in words:
if w.lower() == 'catholic' or w.lower() == 'mother': # Convert word to lowercase for
comparison
count += 1
print('Count of Catholic, mother is', count)
f.close() # Close the file

Page 13 of 36
9. Write a method/function COUNTLINES_ET() in Python to read lines from a text file
“REPORT.TXT”, and count those lines which start with ‘E’ and those which start with ‘T’,
displaying the total count separately.

Answer-
def COUNTLINES_ET():
f = open("REPORT.TXT", "r") # Open the file in read mode
d = f.readlines()
le = 0
lt = 0
for i in d:
if i[0] == 'E': # Check if line starts with 'E'
le += 1
elif i[0] == 'T': # Check if line starts with 'T'
lt += 1
print("No of lines starting with E:", le)
print("No of lines starting with T:", lt)
f.close() # Close the file

10. Write a method/function SHOW_TODO() in Python to read contents from a text file “ABC.TXT”
and display those lines that contain the words “TO” or “DO”.

Answer-
def SHOW_TODO():
f = open("ABC.TXT", "r") # Open the file in read mode
d = f.readlines()
for i in d:
if "TO" in i or "DO" in i: # Check if "TO" or "DO" is in the line
print(i, end="") # Print the line without extra newlines
f.close() # Close the file

11. Write a function in Python that counts the number of “Me” or “My” words present in a text file
“STORY.TXT”.

Answer-
def displayMeMy():
num = 0
f = open("story.txt", "rt") # Open the file in read mode
N = f.read()
M = N.split()

for x in M:
if x == "Me" or x == "My": # Check if word is "Me" or "My"
print(x)
num += 1 # Increment the count

print("Count of Me/My in file:", num) # Display final count


f.close() # Close

Page 14 of 36
12. Write a function AMCount() in Python, which should read each character of a text file
STORY.TXT, and count and display the occurrences of alphabets A and M (including small cases
a and m too).

Answer-
def AMCount():
f = open("story.txt", "r") # Open the file in read mode
A, M = 0, 0
r = f.read()

for x in r.split(): # Split text into words


if x[0] == "A" or x[0] == "a":
A += 1
elif x[0] == "M" or x[0] == "m":
M += 1

print("A or a:", A)
print("M or m:", M)

f.close() # Close the file

13. Write a function in Python that displays the number of lines starting with ‘H’ in the file “para.txt”.

Answer-
def countH():
f = open("para.txt", "r") # Open the file in read mode
lines = 0
l = f.readlines()

for i in l:
if i[0] == 'H': # Corrected the assignment operator '=' to comparison '=='
lines += 1

print("No of lines starting with 'H':", lines)

f.close() # Close the file

14. Write a function countmy() in Python to read the file Data.txt and count the number of times “my”
occurs in the file.

Answer-
def countmy():
f = open("Data.txt", "r") # Open the file in read mode
count = 0
x = f.read()
word = x.split()

for i in word:
if i == "my": # Checking if the word is "my"
count += 1

print("my occurs", count, "times")

Page 15 of 36
f.close() # Close the file

15. Write a Python program to find the number of lines in a text file ‘abc.txt’.

Answer-
def count_lines():
f = open("abc.txt", "r") # Open the file in read mode
d = f.readlines() # Read all lines into a list
count = len(d) # Count the number of lines
print(count) # Print the line count
f.close() # Close the file

16. Write a Python program to count the word “if” in a text file ‘abc.txt’.

Answer-
file = open("abc.txt", "r") # Open the file in read mode
c = 0 # Initialize counter
line = file.read() # Read the entire file content
word = line.split() # Split content into words

for w in word:
if w == 'if': # Check if the word is 'if'
print(w) # Print the word
c += 1 # Increment counter

print(c) # Print total count of 'if'


file.close() # Close the file

17. Write a function VowelCount() in Python, which should read each character of a text file
MY_TEXT_FILE.TXT, and count and display the occurrence of vowels (A, E, I, O, U).

Answer-
def VowelCount():
count_a = count_e = count_i = count_o = count_u = 0
f = open('MY_TEXT_FILE.TXT', 'r') # Open file in read mode
d = f.read() # Read file content

for letter in d: # Iterate through each character


if letter.upper() == 'A':
count_a += 1
elif letter.upper() == 'E':
count_e += 1
elif letter.upper() == 'I':
count_i += 1
elif letter.upper() == 'O':
count_o += 1
elif letter.upper() == 'U':
count_u += 1

Page 16 of 36
# Print the vowel counts
print("A or a:", count_a)
print("E or e:", count_e)
print("I or i:", count_i)
print("O or o:", count_o)
print("U or u:", count_u)

f.close() # Close the file

18. Write a function filter(oldfile, newfile) that copies all the lines of a text file “source.txt” onto
“target.txt”, except those lines which start with the “@” sign.

Answer-
def filter(oldfile, newfile):
f1 = open(oldfile, "r") # Open old file in read mode
f2 = open(newfile, "w") # Open new file in write mode

while True:
text = f1.readline()
if len(text) == 0: # Break loop if end of file
break
if text[0] == '@': # Skip lines starting with '@'
continue
f2.write(text) # Write valid lines to new file

f1.close() # Close file 1


f2.close() # Close file 2

Binary Files :-
1. Write a definition for function Itemadd () to insert record into the binary file ITEMS.DAT,
(items.dat- id,gift,cost). info should stored in the form of dictionary.

Answer-
import pickle
def itemadd ():
f=open("items.dat","wb")
n=int(input("enter how many records"))
for i in range(n):
r=int(input('enter id'))
n=input("enter gift name")
p=float(input("enter cost"))
v={"id":r,"name":n,"cost":p}
pickle.dump(v,f)
f.close()

Page 17 of 36
2. Write a definition for function SHOWINFO() to read each record of a binary file
ITEMS.DAT,
(items.dat- id,gift,cost).Assume that info is stored in the form of dictionary

Answer-
import pickle
def SHOWINFO():
f=open("items.dat","rb")
while True:
try:
g=pickle.load(f)
print(g)
except:
break
f.close()

#---------------------OR------------------
def SHOWINFO():
f=open("items.dat","rb")
while True:
try:
g=pickle.load(f)
print("item id",g['id'],"gift name",g['name'],"cost",g['cost'])
except:
break
f.close()

3. Write a definition for function COSTLY() to read each record of a binary file
ITEMS.DAT, find and display those items, which are priced less than 50.
(items.dat- id,gift,cost).Assume that info is stored in the form of dictionary

Answer-

def COSTLY():
f=open("items.dat","rb")
while True:
try:
r=pickle.load(f)
if(r['cost']<50):
print(r)
except:
break
f.close()

4. Write a definition for function COSTLY() to read each record of a binary file
ITEMS.DAT, find and display those items, which are priced more than 50.
(items.dat- id,gift,cost).Assume that info is stored in the form of list

Answer-
def COSTLY():

Page 18 of 36
f=open("items.dat","rb")
while True:
try:
r=pickle.load(f)
if(r['cost']>50):
print(r)
except:
break
f.close()

5. Write a definition for function COSTLY() to read each record of a binary file
ITEMS.DAT, find and display those items, which are priced between 50 to 60.
(items.dat- id,gift,cost).Assume that info is stored in the form of dictionary

Answer-
def COSTLY():
f=open("items.dat","rb")
while True:
try:
r=pickle.load(f)
if(r['cost']>=50 and r['cost']<=60):
print(r)
except:
break
f.close()

6. Write a function for function to SEARCH()for a item from a binary file "items.dat"
The user should enter the itemno and function should search and
display the detail of items.(items.dat- id,gift,cost).
Assume that info is stored in the form of dictionary

Answer-
import pickle
def SEARCH():
f=open("items.dat","rb")
n=int(input("enter itemno which u want to search"))
while True:
try:
r=pickle.load(f)
if(r['id']==n):
print(r)
except:
break
f.close()

7. Write a function for function to SEARCH()for a item from a binary file "items.dat"
The user should enter the item name and function should search and
display the detail of items.(items.dat- id,gift,cost).
Assume that info is stored in the form of dictionary

Page 19 of 36
Answer-
import pickle
def SEARCH():
f=open("items.dat","rb")
n=input("enter gift name which u want to search")
while True:
try:
r=pickle.load(f)
if(r['gift']==n):
print(r)
except:
break
f.close()

8. Write a function in to search and display details of all flights, whose


destination is “Mumbai” from a binary file “FLIGHT.DAT”.
(flight.dat- fno,from (starting point), to (destination)).
Assume that info is stored in the form of dictionary

import pickle
def FUN():
f=open("FLIGHT.DAT","rb")

while True:
try:
r=pickle.load(f)
if(r['to']=="Mumbai"):
print(r)
except:
break
f.close()

9. write a function TOTALTeachers() to read each record of a binary file TEACH.DAT,


find the total no of teachers, whose data is stored in the file and
display the same.(TEACH.DAT contains : scode,sname,NOT (#no of teachers)).
Assume that info is stored in the form of dictionary

Answer-
import pickle
def TOTALTeachers():
f=open("TEACH.DAT","rb")
c=0
while True:
try:
r=pickle.load(f)
c=c+1
print(r)
except:
break

Page 20 of 36
print(c)
f.close()

10. Write a function in that would read the contents from the file GAME.DAT and
creates a file named BASKET.DAT copying only those records from GAME.DAT where
the game name is “BasketBall―.(game.dat - gamename, participants).
Assume that info is stored in the form of dictionary

Answer-
import pickle
def fun():
f=open("GAME.DAT","rb")
f1=open("BASKET.DAT","wb")
while True:
try:
r=pickle.load(f)
if(r['gamename']=="BasketBall"):
pickle.dump(r,f1)
except:
break
print(c)
f.close()
f1.close()

11. Write a function in to read and display the detail of all the members whose
membership type is ‘L’ or ‘M’ from a binary file “CLUB.DAT―.
(CLUB.dat contains the following info-
mno,type (l for life member M monthly member),mname).
Assume that info is stored in the form of dictionary

Answer-
import pickle
def fun():
f=open("CLUB.DAT","rb")
while True:
try:
r=pickle.load(f)
if(r['type']=="L" or r['type']=="M"):
print(r)
except:
break
print(c)
f.close()

11. Write a definition for function DELETEINFO() from binary file


ITEMS.DAT. The user should enter the itemno and function should search and
delete the entered itemno info
(items.dat- id,gift,cost).
Assume that info is stored in the form of dictionary

Page 21 of 36
Answer-
import pickle
import os
def DELETEINFO():
f=open("items.dat","rb")
f2=open("temp.dat","wb")
a=int(input("enter item id which you want to delete"))
while True:
try:
r=pickle.load(f)
if(r['id']!=a):
pickle.dump(r,f2)
except:
break
f.close()
f2.close()
os.remove("items.dat")
os.rename("temp.dat","items.dat")

12. Write a definition for function DELETEINFO() from binary file


ITEMS.DAT. The user should enter the item name and function should search and
delete the entered itemno info
(items.dat- id,gift,cost).
Assume that info is stored in the form of dictionary

Answer-
import pickle
import os
def DELETEINFO():
f=open("items.dat","rb")
f2=open("temp.dat","wb")
a=input("enter gift name which you want to delete")
while True:
try:
r=pickle.load(f)
if(r['gift']!=a):
pickle.dump(r,f2)
except:
break
f.close()
f2.close()
os.remove("items.dat")
os.rename("temp.dat","items.dat")

13. Write a definition for function UPDATEINFO() from binary file


ITEMS.DAT. The user should enter the item name and function should search and
update the entered itemno info
(items.dat- id,gift,cost).
Assume that info is stored in the form of dictionary

Page 22 of 36
Answer-

import pickle
import os
def UPDATEINFO():
f=open("items.dat","rb")
f2=open("temp.dat","wb")
s=[]
a=input("enter item name which we want to update")
while True:
try:
r=pickle.load(f)
if(r['gift']==a):
r['id']=int(input("enter new item id"))
r['name']=input("enter item name")
r['cost']=int(input("enter cost of item"))
s.append(r)
except:
break
pickle.dump(s,f2)
f.close()
f2.close()
os.remove("items.dat")
os.rename("temp.dat","items.dat")

14. 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 roll number as a
parameter and searches the record in the file “student.dat” and shows the details of the student (if
found) otherwise shows the message as ‘No record found’.
Answer-
import pickle

# Function to insert a record into the binary file


def insertRec():
f = open("student.dat", "ab") # Open file in append binary mode
rollno = int(input("Enter Roll Number: "))
name = input("Enter Name: ")
marks = int(input("Enter Marks: "))
rec = [rollno, name, marks] # Store data in a list
pickle.dump(rec, f) # Write record to file
f.close() # Close file

# Function to search for a record by Roll Number


def searchRollNo(r):
f = open("student.dat", "rb") # Open file in read binary mode
flag = False
while True:
try:
rec = pickle.load(f) # Read record
if rec[0] == r:

Page 23 of 36
print("Roll Number:", rec[0])
print("Name:", rec[1])
print("Marks:", rec[2])
flag = True # Record found
except EOFError: # End of file reached
break
if not flag:
print("No record found")
f.close() # Close file

15. 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 create a file emp.dat. ii. Write a function display() in Python to
display the detail of all employees whose salary is more than 50000.

Answer-
import pickle

# Function to create an employee record and save it to a binary file


def CreateEmp():
f1 = open("emp.dat", 'wb') # Open file in write binary mode
eid = input("Enter Employee ID: ")
ename = input("Enter Name: ")
designation = input("Enter Designation: ")
salary = int(input("Enter Salary: "))
l = [eid, ename, designation, salary] # Store employee details in a list
pickle.dump(l, f1) # Write list to file
f1.close() # Close file

# Function to display records where salary is greater than 5000


def display():
f2 = open("emp.dat", "rb") # Open file in read binary mode
try:
while True:
rec = pickle.load(f2) # Read record from file
if rec[3] > 5000: # Check salary condition
print(rec[0], rec[1], rec[2], rec[3])
except EOFError: # End of file reached
f2.close() # Close file

16. i. A binary file “emp.DAT” has structure (EID, Ename, designation,salary). Write a function to add more
records of employes in existing file 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 “Salesman”.
Answer-
import pickle

# Function to create and append employee records


def createemp():
f1 = open("emp.dat", 'ab') # Open file in append binary mode
eid = input("Enter Employee ID: ")
ename = input("Enter Name: ")
designation = input("Enter Designation: ")
salary = int(input("Enter Salary: "))
l = [eid, ename, designation, salary] # Store employee details in a list

Page 24 of 36
pickle.dump(l, f1) # Write list to file
f1.close() # Close file

# Function to display employees with designation "Manager"


def display():
f2 = open("emp.dat", "rb") # Open file in read binary mode
try:
while True:
rec = pickle.load(f2) # Read record from file
if rec[2] == 'Manager': # Check if designation is "Manager"
print(rec[0], rec[1], rec[2], rec[3]) # Print the record
except EOFError: # End of file reached
pass
f2.close() # Close file

17. A binary file named “EMP.dat” has some records of the structure [EmpNo, EName, Post, Salary] (a) Create
a binary file “EMP.dat” that stores the records of employees and display them one by one. (b) Display the
records of all those employees who are getting salaries between 25000 to 30000.
Answer-
# (a) Read and display all records from "emp.dat"
import pickle

f1 = open('emp.dat', 'rb')
try:
while True:
e = pickle.load(f1) # Load record from file
print(e) # Print the record
except EOFError: # End of file reached
pass
finally:
f1.close() # Close file

# (b) Read and display records with salary between 25000 and 30000
import pickle

f1 = open('emp.dat', 'rb')
try:
while True:
e = pickle.load(f1) # Load record from file
if 25000 <= e[3] <= 30000: # Check if salary is in the range
print(e) # Print the record
except EOFError: # End of file reached
pass
finally:
f1.close() # Close file

18. 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”
Answer-
# (i) Function to create and store book records
import pickle

Page 25 of 36
def createFile():
f = open("Book.dat", "ab") # Open file in append-binary mode
BookNo = int(input("Book Number: "))
Book_Name = input("Name: ")
Author = input("Author: ")
Price = int(input("Price: "))
rec = [BookNo, Book_Name, Author, Price] # Store data as a list
pickle.dump(rec, f) # Dump record into file
f.close() # Close file

# (ii) Function to count the number of books by a specific author


def CountRec(author_name):
f = open("Book.dat", "rb") # Open file in read-binary mode
num = 0
try:
while True:
rec = pickle.load(f) # Read record from file
if author_name == rec[2]: # Compare author name
num += 1
except EOFError: # Handle end-of-file error
pass
finally:
f.close() # Close file
return num # Return count of books by given author

19. A binary file student.dat has structure (rollno,name,class,percentage). Write a program to updating a record
in the file requires roll number to be fetched from the user whose name is to be updated
Answer-
import pickle
import os

# Function to update a student's name based on roll number


def updateStudent():
f1 = open("student.dat", "rb") # Open original file in read-binary mode
f2 = open("temp.dat", "wb") # Open temp file in write-binary mode
r = int(input("Enter roll number to update: "))

try:
while True:
e = pickle.load(f1) # Read record
if e[0] == r: # Check if roll number matches
e[1] = input("Enter new name: ") # Update name
pickle.dump(e, f2) # Write record to new file
except EOFError:
pass # End of file reached

f1.close()
f2.close()

os.remove("student.dat") # Remove old file


os.rename("temp.dat", "student.dat") # Rename new file

Page 26 of 36
20. 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

Answer-
# Function to count and display students with percentage > 75
def CountRec():
f = open("STUDENT.DAT", "rb") # Open file in read-binary mode
num = 0 # Counter for students scoring above 75%

try:
while True:
rec = pickle.load(f) # Read record
if rec[2] > 75: # Check percentage
print(rec[0], rec[1], rec[2]) # Display student details
num += 1 # Increment count
except EOFError:
pass # End of file reached
finally:
f.close() # Close file

print(f"Total students scoring above 75%: {num}")


return num

20. A binary file named “EMP.dat” has some records of the structure [EmpNo, EName, Post, Salary] (a) Write
a user-defined function named NewEmp() to input the details of a new employee from the user and store it
in EMP.dat. (b) 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.
Answer-
import pickle

# (a) Function to create and store a new employee record


def NewEmp():
f = open("EMP.dat", "wb") # Open file in write-binary mode
EmpNo = int(input("Enter employee number: "))
EName = input("Enter name: ")
Post = input("Enter post: ")
Salary = int(input("Enter salary: "))
rec = [EmpNo, EName, Post, Salary] # Corrected variable name `EName`
pickle.dump(rec, f) # Write record to file
f.close() # Close file

# (b) Function to calculate and display sum of salaries for a given post
def SumSalary(Post):
f = open("EMP.dat", "rb") # Open file in read-binary mode
c = 0 # Variable to store sum of salaries
try:
while True:
g = pickle.load(f) # Read record
if g[2] == Post: # Check if post matches
c += g[3] # Add salary
except EOFError:
pass # End of file reached

Page 27 of 36
finally:
f.close() # Close file

print("Sum of salary for", Post, ":", c) # Display total salary

21. A binary file “Items.dat” has structure as [ Code, Description, Price ]. i. Write a user defined function
MakeFile( ) to input multiple items from the user and add to Items.dat ii. Write a function SearchRec(Code)
in Python which will accept the code as parameter and search and display the details of the corresponding
code on screen from Items.dat.
Answer-
import pickle

# (i) Function to create and store item records in a binary file


def MakeFile():
while True:
code = input("Enter Item Code: ")
desc = input("Enter description: ")
price = float(input("Enter price: "))
d = [code, desc, price]

with open("Items.dat", "ab") as f: # Open file in append-binary mode


pickle.dump(d, f) # Write record to file

ch = input("Add more records? (y/n): ")


if ch.lower() == 'n': # Check for lowercase 'n' to handle input variations
break

# (ii) Function to search for an item by code in the binary file


def SearchRec(code):
found = False
try:
with open("Items.dat", "rb") as f: # Open file in read-binary mode
while True:
g = pickle.load(f) # Read record
if g[0] == code: # Check if the item code matches
print(g[0], g[1], g[2])
found = True
break # Stop searching once found
except EOFError:
pass # End of file reached
except FileNotFoundError:
print("File not found!")

if not found:
print("No such record found.")

22. A binary file “Bank.dat” has structure as [account_no, cust_name, balance]. i. Write a user-defined
function addfile( ) and add a record to Bank.dat. ii. Create a user-defined function CountRec( ) to count and
return the number of customers whose balance amount is more than 100000Answer-
Answer-
import pickle

Page 28 of 36
def addfile():
with open("bank.dat", "ab") as f: # Open file in append-binary mode
acc_no = int(input("Enter account number: "))
cust_name = input("Enter name: ")
bal = int(input("Enter balance: "))
rec = [acc_no, cust_name, bal]
pickle.dump(rec, f) # Store record in file
def CountRec():
c=0
try:
with open("bank.dat", "rb") as f: # Open file in read-binary mode
while True:
rec = pickle.load(f) # Read record
if rec[2] > 100000: # Check balance condition
c += 1
except EOFError:
pass # End of file reached
except FileNotFoundError:
print("File not found!")

return c # Return count of matching records

CSV Files
1.Write a Program in Python that defines and calls the following user defined functions:
(i)ADDPROD( ) – To accept and add data of a product to a CSV file ‘product.csv’. Each record
consists of a list with field elements as prodid, name and price to store product id, employee name
and product price respectively.
(ii)COUNTPROD( ) – To count the number of records present in the CSV file named
‘product.csv’.

Answer-
import csv

def ADD():
fout = open("record.csv", "a", newline="")
wr = csv.writer(fout)
empid = int(input("Enter Employee ID: "))
name = input("Enter Name: ")
mobile = int(input("Enter Mobile Number: "))
lst = [empid, name, mobile] # Corrected variable name
wr.writerow(lst)
fout.close()

def COUNTR():
fin = open("record.csv", "r", newline="")
data = csv.reader(fin)
d = list(data)
print(len(d))
fin.close()

Page 29 of 36
ADD()
COUNTR()

2. Write a Program in Python that defines and calls the following user defined functions:
(i) add() – To accept and add data of a to a CSV file ‘stud.csv’. Each record consists of a list with
field elements as admno, sname and per to store admission number, student name and percentage
marks respectively.
(ii) search()- To display the records of the students whose percentage is more than 75.

Answer-
import csv

def add():
"""Function to add student records to 'stud.csv'"""
fout = open("stud.csv", "a", newline="")
wr = csv.writer(fout)

admno = int(input("Enter Admission Number: "))


sname = input("Enter Student Name: ")
per = float(input("Enter Percentage: "))

lst = [admno, sname, per]


wr.writerow(lst)
fout.close()

def search():
"""Function to display students with percentage > 75"""
fin = open("stud.csv", "r", newline="")
data = csv.reader(fin)

print("Students with percentage > 75:")


for record in data:
if len(record) == 3 and float(record[2]) > 75:
print(record)

fin.close()

# Calling the functions


add()
search()

3.Manoj Kumar of class 12 is writing a program to create a CSV file “user.csv” which will
contain user name and password for some entries. He has written the following code. As a
programmer, help him to successfully execute the given task.

import ______________________________ #Line1


def addCsvFile(UserName, Password):
fh=open('user.csv','_________________________ ') #Line2
Newfilewriter=csv.writer(fh) Newfilewriter.writerow([UserName,Password])

Page 30 of 36
fh.close( ) # csv file reading code

def readCsvFile(): #to read data from CSV file


with open('user.csv','r') as newFile:
newFileReader=csv.______________________(newFile) #Line3
for row in newFileReader:

print(row) newFile.__________________________ #Line4


addCsvFile('Arjun','123@456')
addCsvFile('Arunima','aru@nima')
addCsvFile('Frieda','myname@FRD')
readCsvFile()

(a)What module should be imported in #Line1 for successful execution of the program?
import csv
(b)In which mode file should be opened to work with user.csv file in#Line2
fh = open('user.csv', 'a', newline='')
(c)Fill in the blank in #Line3 to read data from csv file
newFileReader = csv.reader(newFile)
(d)Fill in the blank in #Line4 to close the file
newFile.close()

Answer-
import csv # Line1

def addCsvFile(UserName, Password):


fh = open('user.csv', 'a', newline='') # Line2
Newfilewriter = csv.writer(fh)
Newfilewriter.writerow([UserName, Password])
fh.close()

def readCsvFile(): # To read data from CSV file


with open('user.csv', 'r') as newFile:
newFileReader = csv.reader(newFile) # Line3
for row in newFileReader:
print(row)
newFile.close() # Line4

# Adding records
addCsvFile('Arjun', '123@456')
addCsvFile('Arunima', 'aru@nima')
addCsvFile('Frieda', 'myname@FRD')

# Reading records
readCsvFile()

4. Radha Shah is a programmer, who has recently been given a task to write a python code to
perform the following CSV file operations with the help of two user defined functions/modules:

(a) CSVOpen() : to create a CSV file called “ books.csv” in append mode containing information
of books – Title, Author and Price.

Page 31 of 36
(b) CSVRead() : to display the records from the CSV file called “ books.csv” .where the field title
starts with 'R'. She has succeeded in writing partial code and has missed out certain statements,
so she has left certain queries in comment lines.

import csv
def CSVOpen( ):
with open('books.csv','____________',newline='') as csvf: #Statement-1
cw= csv.writer(csvf)
_________________ #Statement-2

cw.writerow(['Rapunzel','Jack',300])
cw.writerow(['Barbie','Doll',900])
cw.writerow(['Johnny','Jane',280])

def CSVRead( ):
try:
with open('books.csv','r') as csvf:
cr= ______________________ #Statement-3
for r in cr:

if____________ : #Statement-4
print(r)
except:
print('File Not Found')
CSVOpen( )
CSVRead( )

You as an expert of Python have to provide the missing statements and other related queries based
on the following code of Radha.
(a) Write the appropriate mode in which the file is to be opened in append mode (Statement 1)
(b) Write the correct option for Statement 2 to write the names of the column headings in the
CSV file, books.csv
(c) Write statement to be used to read a csv file in Statement 3.
(d) Fill in the appropriate statement to check the field Title starting with „R‟ for Statement 4 in
the above program.

Answer-
a) with open('books.csv', 'a', newline='') as csvf:
b) cw.writerow(['Title', 'Author', 'Price'])
c) cr = csv.reader(csvf)
d) if r[0].startswith('R'):

5. Vedansh is a Python programmer working in a school. For the Annual Sports Event, he has
created a csv file named Result.csv, to store the results of students in different sports events. The
structure of Result.csv
is :
[St_Id, St_Name, Game_Name, Result]
Where
St_Id is Student ID (integer)
ST_name is Student Name (string)
Game_Name is name of game in which student is participating(string)
Result is result of the game whose value can be either 'Won', 'Lost' or 'Tie'

Page 32 of 36
For efficiently maintaining data of the event, Vedansh wants to write the following user defined
functions:
Accept() – to accept a record from the user and add it to the file Result.csv. The column headings
should also be added on top of the csv file.
wonCount() – to count the number of students who have won any event. As a Python expert, help
him complete the task.

Answer-
import csv
import os

def Accept():
sid = int(input("Enter Student ID: "))
sname = input("Enter Student Name: ")
game = input("Enter name of game: ")
res = input("Enter Result (Won/Lost/Tie): ")

headings = ["St_Id", "St_Name", "Game_Name", "Result"]


data = [sid, sname, game, res]

file_exists = os.path.exists("Result.csv") # Check if file exists

with open('Result.csv', 'a', newline='') as f:


csvwriter = csv.writer(f)
if not file_exists: # Write headings only if file does not exist
csvwriter.writerow(headings)
csvwriter.writerow(data)

def wonCount():
count = 0
try:
with open('Result.csv', 'r') as f:
csvreader = csv.reader(f)
next(csvreader) # Skip header row
for row in csvreader:
if len(row) > 3 and row[3].strip().lower() == "won": # Case insensitive match
count += 1
print(f"Total students who won an event: {count}")
except FileNotFoundError:
print("File not found! No data available.")

# Function Calls
Accept()
wonCount()

6. What is the advantage of using a csv file for permanent storage?


Write a Program in Python that defines and calls the following user defined
functions:
a) ADD() – To accept and add data of an employee to a CSV file ‘record.csv’. Each record
consists of a list with field elements as empid, name and mobile to store employee id, employee
name and employee salary respectively.
b) COUNTR() – To count the number of records present in the CSV file named ‘record.csv’.

Page 33 of 36
Program:
import csv
def ADD():
fout = open("record.csv", "a", newline="\n")
wr = csv.writer(fout)
empid = int(input("Enter Employee id: "))
name = input("Enter name: ")
mobile = int(input("Enter mobile number: "))
lst = [empid, name, mobile]
wr.writerow(lst)
fout.close()
def COUNTR():
fin = open("record.csv", "r", newline="\n")
data = csv.reader(fin)
next(data) # Skip the header row if present
d = list(data)
print("Number of records:", len(d))
fin.close()
ADD()
COUNTR()

7. Give any one point of difference between a binary file and a csv file.
Write a Program in Python that defines and calls the following user defined functions:
a) add() – To accept and add data of an employee to a CSV file ‘furdata.csv’. Each record consists
of a list with field elements as fid, fname and fprice to store furniture id, furniture name and
furniture price respectively.
b) search()- To display the records of the furniture whose price is more than 10000.

Answer-
import csv
import os

# Function to add employee data to furdata.csv


def add():
fid = input("Enter Furniture ID: ")
fname = input("Enter Furniture Name: ")
fprice = float(input("Enter Furniture Price: "))

data = [fid, fname, fprice]


file_exists = os.path.exists("furdata.csv") # Check if file exists

with open("furdata.csv", "a", newline="") as f:


csvwriter = csv.writer(f)
if not file_exists: # Write headings only if file does not exist
csvwriter.writerow(["FID", "FName", "FPrice"])
csvwriter.writerow(data)
print("Furniture record added successfully!\n")

# Function to search for furniture with price > 10000


def search():

Page 34 of 36
try:
with open("furdata.csv", "r") as f:
csvreader = csv.reader(f)
next(csvreader) # Skip header row
found = False
print("\nFurniture items with price more than 10000:")
for row in csvreader:
if len(row) > 2 and float(row[2]) > 10000:
print(row)
found = True
if not found:
print("No furniture items found with price more than 10000.")
except FileNotFoundError:
print("File not found! No data available.")

# Function Calls
add()
search()

8. Ranjan Kumar of class 12 is writing a program to create a CSV file “user.csv” which will
contain user name and password for some entries. He has written the following code. As a
programmer, help him to successfully execute the given task.
import _____________ # Line 1
def addCsvFile(UserName,PassWord): # to write / add data into the
CSV file
f=open(' user.csv','________') # Line 2
newFileWriter = csv.writer(f)
newFileWriter.writerow([UserName,PassWord])
f.close()
#csv file reading code
def readCsvFile(): # to read data from CSV file
with open(' user.csv','r') as newFile:
newFileReader = csv._________(newFile) # Line 3
for row in newFileReader:
print (row[0],row[1])
newFile.______________ # Line 4
addCsvFile(“Arjun”,”123@456”)
addCsvFile(“Arunima”,”aru@nima”)
addCsvFile(“Frieda”,”myname@FRD”)
readCsvFile() #Line 5
(a) Name the module he should import in Line 1.
(b) In which mode, Ranjan should open the file to add data into the file
(c) Fill in the blank in Line 3 to read the data from a csv file.
(d) Fill in the blank in Line 4 to close the file.
(e) Write the output he will obtain while executing Line 5.

Answer –

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


→ csv

Page 35 of 36
(b) In which mode should Ranjan open the file to add data?
→ 'a' (append mode) to add new entries without overwriting existing data

(c) Fill in the blank in Line 3 to read the data from a CSV file.
→ csv.reader(newFile)

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


→ close()

(e) Expected Output on executing Line 5:

Arjun 123@456
Arunima aru@nima
Frieda myname@FRD

*****************************

Page 36 of 36

You might also like