Data File Handling-Question Bank
Data File Handling-Question Bank
3. After using this method, an opened file 4. if our program is large and we are
will be closed and a closed file cannot reading or writing multiple files that can
be read or written any more. take significant amount of resource on
the system. If we keep opening new files
carelessly, we could run out of
resources.
syntax:
with open(<file_name>, <access_mode>) as
file_object/file_handler
Q Name two important functions of CSV module which are used for reading and writing.
csv.reader() returns a reader object which iterates over lines of a CSV file
csv.writer() returns a writer object that converts the user's data into a delimited string. This string can later be used to write
into CSV files using the writerow() or the writerows() function.
r+ and w+
r+ w+
Opens a file for reading and writing, placing the Opens a file for writing and reading, overwrites
pointer at the beginning of the file. the existing file if the file exists. If the
file does not exist, creates a new file for writing
and reading
r and a
r a
Reading only for appending
Sets file pointer at beginning of the file Move file pointer at end of the file
This is the default mode. Creates new file for writing,if not exist
e.g. e.g.
f=open(“abc.dat”,’r’) f=open(“abc.dat”,’a’)
TEXT FILE AND BINARY FILE
A text file is simply a sequence of ASCII or Unicode Best way to store program information.
characters.
EOL (new line character i.e. enter) or internal No EOL or internal translation occurs( not converted
translation occurs into other form becoz it is converted into computer
understandable form i.e. in binary format)
e.g. Python programs, contents written in text editors e.g. exe files,mp3 file, image files, word documents
seek() tell()
takes the file pointer to the specified byte it gives current position within file
position
Syntax: Syntax
seek(“no_of_bytes_to_move”, “from_where”) fileobjectname.tell()
Example:
“from_where”- has 3 values f.tell()
A text file is simply a sequence Can store different types of They are plain text files having
of ASCII or Unicode characters. data (audio, text,image) in a ASCII/Unicode Characters
single file.
EOL (new line character i.e. No EOL occurs Language which support text
enter) or internal translation files will also support csv files.
occurs
‘w’ ‘a’
'w' Open a file for writing 'a' Open for appending at the end of the file
without truncating it.
Creates a new file if it does not exist or truncates Creates a new file if it does not exist.
the file if it exists.
write() writelines()
write() function write a single string at a time writelines() methods can be used to write a
sequence of strings
PICKLING AND UNPICKLING
PICKLING UNPICKLING
Pickling is the process whereby a Python object is Unpickling is the process by which a byte stream
converted into a byte stream. is converted back into the desired object.
readline() and readlines()
readline() readlinelines()
The readline() method reads one line(i.e. till The readlines()method reads the entire content
newline) at a time from a file and returns that of the file in one go and returns a list of lines of
line the entire file.
It reads the file till newline including the newline
character.
The readline() method returns an empty string This method returns an empty value when an end
when the end of file is reached. of file (EOF) is reached.
or
f=open(“firewall.txt")
for i in range(3):
print(f.readline())
for i in r:
if(i>='a' and i<='z'):
f1.write(i)
Write a program in python to read first 5 elif(i>='A' and i<='Z'):
characters from the file("data.txt") f2.write(i)
else:
f=open(“data.txt”,”r”) f3.write(i)
d=f.read(5) f.close()
print(d) f1.close()
f2.close()
f3.close()
Write a program in python to display number of Write a program in python to display first line
lines in a file("data.txt"). from the file("data.txt") using readlines().
f=open(“data.txt”,”r”) f=open(“data.txt”,”r”)
d=f.readlines() d=f.readlines()
print(d) print(d[0])
Write a program in python to display first Write a program in python to display all the lines
character of all the lines from the file("data.txt"). from the file("data.txt") with first character in
f=open(“data.txt”,”r”) uppercase.
d=f.readlines() f=open(“data.txt”,”r”)
for i in d: d=f.readlines()
print(i[0]) for i in d:
print(i[0].upper+i[1:-1]))
Write a program in python to find the number of Write a program in python to display last two
characters in first line of file ("data.txt") characters of all the lines from the
f=open(“data.txt”,’r’) file("data.txt").
t=f.readline()
print(len(t)) f=open(“data.txt”,’r’)
t=f.readlines()
for i in t:
print(i[-3:])
Write a program to read all the characters from Write a program to count all the upper case
the file("data.txt") and display in uppercase. characters from the file ("data.txt").
f=open(“data.txt”,’r’) f=open(“data.txt”,’r’)
t=f.read() t=f.read()
print(t.upper()) c=0
for i in t:
if(i.isupper()):
c=c+1
print(“total uppercase characters”,c)
Write a program to count number of spaces from Write a program to count number of vowels in a
the file ("data.txt"). file ("data.txt").
f =open(“data.txt”,’r’)
t=f.read() f =open(“data.txt”,’r’)
c=0 t=f.read()
for i in t: c=0
if(i.isspace() and i!=’\n’): for i in t:
c=c+1 if(i==’a’ or i==’e’ or i==’o’ or i==’i’ or i==’u’):
print(“total spaces”,c) c=c+1
print(“total spaces”,c)
Write a function in python to count the number Write a user defined function countwords() to
lines in a text file ‘Country.txt’ which is starting display the total number of words present in the
with an alphabet ‘W’ or ‘H’. file from a text file “Quotes.Txt”.
def count_W_H():
f = open (“Country.txt”, “r”) def countwords():
W,H = 0,0 s = open("Quotes.txt","r")
r = f.read() f = s.read()
for x in r: z = f.split ()
if x[0] == “W” or x[0] == “w”: count = 0
W=W+1 for i in z:
elif x[0] == “H” or x[0] == “h”: count = count + 1
H=H+1 print ("Total number of words:", count)
f.close()
print (W, H)
Write a user defined function countwords() to Write a function COUNT_AND( ) in Python to read
display the total number of words present in the the text file “STORY.TXT” and count the number
file from a text file “Quotes.Txt”. of times “AND” occurs in the file. (include
def countwords(): AND/and/And in the counting)
s = open("Quotes.txt","r") def COUNT_AND( ):
f = s.read() count=0
z = f.split () file=open(‘STORY.TXT','r')
count = 0 line = file.read()
for i in z: word = line.split()
count = count + 1 for w in word:
print ("Total number of words:", count) if w ==’AND’:
count=count+1
print(count)
file.close()
Write a function DISPLAYWORDS( ) in python to Write a function that counts and display the
display the count of words starting with “t” or “T” number of 5 letter words in a text file “Sample.txt
in a text file ‘STORY.TXT’. def count_words( ):
def COUNT_AND( ): c=0
count=0 f = open("Sample.txt")
file=open(‘STORY.TXT','r') line = f.read()
line = file.read() word = line.split()
word = line.split() for w in word:
for w in word: if len(w) == 5:
if w[0] ==’t’ or w*0+==’T’: c += 1
count=count+1 print(c)
print(count)
file.close()
Write a function that counts and display the Write a function that counts and display the
number of 5 letter words in a text file “Sample.txt number of 5 letter words in a text file “Sample.txt
def count_words( ): def count_words( ):
c=0 c=0
f = open("Sample.txt") f = open("Sample.txt")
line = f.read() line = f.read()
word = line.split() word = line.split()
for w in word: for w in word:
if len(w) == 5: if len(w) == 5:
c += 1 c += 1
print(c) print(c)
Write a function that counts and display the Write a function to display those lines which start
number of 5 letter words in a text file “Sample.txt with the letter “G” from the text file
def count_words( ): “MyNotes.txt”
c=0 def count_lines( ):
f = open("Sample.txt") c=0
line = f.read() f = open("MyNotes.txt")
word = line.split() line = f.readlines()
for w in word: for w in line:
if len(w) == 5: if w[0] == 'G':
c += 1 print(w)
print(c) f.close()
f.close()
Write a function in python to read lines from file Write a function COUNT() in Python to read
“POEM.txt” and display all those words, which contents from file “REPEATED.TXT”, to count and
has two characters in it. display the occurrence of the word “Catholic” or
def TwoCharWord(): “mother”.
f = open('poem.txt') def COUNT():
count = 0 f = open('REPEATED.txt')
for line in f: count = 0
words = line.split() for line in f:
for w in words: words = line.split()
if len(w)==2: for w in words:
if w.lower()=='catholic' or w.lower()=='mother':
print(w,end=' ')
f.close() count+=1
print('Count of Catholic,mother is',count)
Write a function in Python that counts the Write a function AMCount() in Python, which
number of “Me” or “My” words present in a text should read each character of a text file
file “STORY.TXT”. STORY.TXT, should count and display the
def displayMeMy(): occurrences of alphabets A and M (including
num=0 small cases a and m too).
f=open("story.txt","rt") def AMCount():
N=f.read() f=open("story.txt","r")
M=N.split() A,M=0,0
for x in M: r=f.read()
if x=="Me" or x== "My": for x in r:
print(x) if x[0]=="A" or x[0]=="a" :
num=num+1 A=A+1
print("Count of Me/My in file:",num) elif x[0]=="M" or x[0]=="m":
f.close() M=M+1
print("A or a: ",A)
f.close()
Write a function in python that displays the Write a function countmy() in Python to read file
number of lines starting with ‘H’ in the file Data.txt and count the number of times “my”
“para.txt”. occur in file.
def countH(): def countmy():
f=open("para.txt","r") f=open(“Data.txt”,”r”)
lines=0 count=0
l=f.readlines() x=f.read()
for i in l: word=x.split()
if i[0]='H': for i in word:
lines+=1 if i ==”my” :
print("NO of lines are:",lines) count=count+1
f.close() print(“my occurs “, count, “times”)
Write a Python program to find the number of Write a Python program to count the word “if “ in
lines in a text file ‘abc.txt’. a text file abc.txt’.
f=open("abc.txt","r") file=open("abc.txt","r")
d=f.readlines() c=0
count=len(d) line = file.read()
print(count) word = line.split()
f.close() for w in word:
if w=='if':
print( w)
c=c+1
print(c)
file.close()
Write a method in python to read lines from a Write a method/function ISTOUPCOUNT() in
text file DIARY.TXT and display those lines which python to read contents from a text file
start with the alphabets P. WRITER.TXT, to count and display the occurrence
def countp(): of the word ‘‘IS’’ or ‘‘TO’’ or ‘‘UP’’
f=open("diary.txt","r")
lines=0 def ISTOUPCOUNT():
l=f.readlines() c=0
for i in l: file=open('sample.txt','r')
if i[0]='P': line = file.read()
lines+=1 word = line.split()
print("No of lines are:",lines) cnt=0
for w in word:
if w=='TO' or w=='UP' or w=='IS':
cnt+=1
print(cnt)
file.close()
Write a code in Python that counts the number of Write a function VowelCount() in Python, which
“The” or “This” words present in a text file should read each character of a text file
“MY_TEXT_FILE.TXT”. MY_TEXT_FILE.TXT, should count and display the
c=0 occurrence of alphabets vowels.
f=open('MY_TEXT_FILE.TXT', 'r') :
d=f.read() def VowelCount():
w=d.split() count_a=count_e=count_i=count_o=count_u=0
for i in w: f= open('MY_TEXT_FILE.TXT', 'r')
if i.upper()== 'THE' or i.upper()== 'THIS' : d=f.read()
c+=1 for i in d:
print(c) if i.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
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)
Write a function filter(oldfile, newfile) that copies
all the lines of a text file “source.txt” onto
“target.txt” except those lines which starts with
“@” sign.
Write a definition for function COSTLY() to read Write a definition for function COSTLY() to read
each record of a binary file each record of a binary file
ITEMS.DAT, find ,count and display those items, ITEMS.DAT, find and display those items, which
which are priced less than 50. are priced between 50 to 60.
(items.dat- id,gift,cost).Assume that info is stored (items.dat- id,gift,cost).Assume that info is stored
in the form of list in the form of list
''' '''
#sol #sol
def COSTLY(): def COSTLY():
f=open("items.dat","rb") f=open("items.dat","rb")
c=0 while True:
while True: try:
try: r=pickle.load(f)
r=pickle.load(f) if(r[2]>=50 and r[2]<=60):
if(r[2]<50): print(r)
c=c+1 except:
print(r) break
except: f.close()
break
print(c)
f.close()
''' '''
Write a function for function to SEARCH()for a Write a function in to search and display details
item from a binary file "items.dat" of all flights, whose
The user should enter the itemno and function destination is “Mumbai” from a binary file
should search and “FLIGHT.DAT”.
display the detail of items.(items.dat- id,gift,cost). (flight.dat- fno,from (starting point), to
Assume that info is stored in the form of list (destination)).
''' Assume that info is stored in the form of list
import pickle '''
def SEARCH(): import pickle
f=open("items.dat","rb") def FUN():
n=int(input("enter itemno which u want to f=open("FLIGHT.DAT","rb")
search"))
while True: while True:
try: try:
r=pickle.load(f) r=pickle.load(f)
if(r[0]==n): if(r[2]=="Mumbai"):
print(r) print(r)
except: except:
break break
f.close() f.close()
''' '''
Write a definition for function UPDATEINFO() Write a function in that would read the contents
from binary file from the file GAME.DAT and
ITEMS.DAT. The user should enter the item name creates a file named BASKET.DAT copying only
and function should search and those records from GAME.DAT where
update the entered itemno info the game name is “BasketBall”.(game.dat -
(items.dat- id,gift,cost). gamename, participants).
Assume that info is stored in the form of list Assume that info is stored in the form of list
''' '''
import pickle import pickle
import os def fun():
def UPDATEINFO(): f=open("GAME.DAT","rb")
f=open("items.dat","rb") f1=open("BASKET.DAT","wb")
f2=open("temp.dat","wb") while True:
s=[] try:
a=input("enter item name which we want to r=pickle.load(f)
update") if(r[0]=="BasketBall"):
while True: pickle.dump(r,f1)
try: except:
r=pickle.load(f) break
if(r[1]==a): print(c)
r[0]=int(input("enter new item id")) f.close()
r[1]=input("enter item name") f1.close()
r[2]=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")
A binary file “student.dat” has structure [rollno, A binary file “emp.dat” has structure [EID,
name, marks]. Ename, designation, salary].
i. Write a user defined function insertRec() to i. Write a user defined function CreateEmp() to
input data for a student and add to student.dat. input data for a record and create a file emp.dat.
ii. Write a function searchRollNo( r ) in Python ii. Write a function display() in Python to display
which accepts the student’s rollno as parameter the detail of all employees whose salary is more
and searches the record in the file “student.dat” than 50000.
and shows the details of student i.e. rollno, name (i)
and marks (if found) otherwise shows the import pickle
message as ‘No record found’. def CreateEmp():
f1=open("emp.dat",'wb')
(i) eid=input("Enter E. Id")
import pickle ename=input("Enter Name")
def insertRec(): designation=input("Enter Designation")
f=open("student.dat","ab") salary=int(input("Enter Salary"))
rollno = int (input("Enter Roll Number : ")) l=[eid,ename,designation,salary]
name=input("Enter Name :") pickle.dump(l,f1)
marks = int(input("Enter Marks : ")) f1.close()
rec = [rollno, name, marks ] (ii)
pickle.dump( rec, f ) import pickle
f.close() def display():
(ii) f2=open("emp.dat","rb")
def searchRollNo( r ): try:
f=open("student.dat","rb") while True:
flag = False rec=pickle.load(f2)
while True: if rec[3]>5000:
try: print(rec[0],rec[1],rec[2],rec[3])
rec=pickle.load(f) except:
if rec[0] == r : f2.close()
print(rec*‘Rollno’+)
print(rec*‘Name’+)
print(rec*‘Marks+)
flag == True
except EOFError:
break
if flag == False:
print(“No record Found”)
f.close()
Write a python program to append a new records Write a python program to search and display the
in a binary file –“student.dat”. The record can record of the student from a binary file
have Rollno, Name and Marks. “Student.dat” containing students records
import pickle (Rollno, Name and Marks). Roll number of the
while True: student to be searched will be entered by the
rollno = int(input("Enter your rollno: ")) user.
name = input("Enter your name: ")
marks = int(input("enter marks obtained: ")) import pickle
d = [rollno, name, marks] f1 = open("Student.dat", "rb")
f1 = open("Student.dat", "wb") rno = int(input(“Enter the roll no to search: ”))
pickle.dump(d, f1) flag = 0
choice = input("enter more records: y/n") try:
if choice== "N": while True:
break r = pickle.load(f1)
f1.close() if rno == r[0]:
print (rollno, name, marks)
flag = 1
except:
if flag == 0:
print(“Record not found…”)
f1.close()
i. A binary file “emp.DAT” has structure (EID, A binary file named “EMP.dat” has some records
Ename, designation,salary). Write a function to of the structure [EmpNo, EName, Post, Salary]
add more records of employes in existing file (a) Create a binary file “EMP.dat” that stores the
emp.dat. records of employees and display them one by
ii. Write a function Show() in Python that would one.
read detail of employee from file “emp.dat” and (b) Display the records of all those employees
display the details of those employee whose who are getting salaries between 25000 to
designation is “Salesman”. 30000.
(i) (a)
import pickle import pickle
def createemp: f1 = open('emp.dat','rb')
f1=open("emp.dat",'ab') try:
eid=input("Enter E. Id") while True:
ename=input("Enter Name") e = pickle.load(f1)
designation=input("Enter Designation") print(e)
salary=int(input("Enter Salary")) except:
l=[eid,ename,designation,salary] f1.close()
pickle.dump(l,f1)
f1.close() (b)
(ii) import pickle
def display(): f1 = open('emp.dat','rb')
f2=open("emp.dat","rb") try:
try: while True:
while True: e = pickle.load(f1)
rec=pickle.load(f2) if(e[3]>=25000 and e[3]<=30000):
if (rec[2]=='Manager'): print(e)
print(rec[0],rec[1], rec[2],rec[3]) except:
except: f1.close()
break
f2.close()
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”
(i)
import pickle
def createFile():
f=open("Book.dat","ab")
BookNo=int(input("Book Number : "))
Book_name=input("Name :")
Author = input("Author:" )
Price = int(input("Price : "))
rec=[BookNo,Book_Name,Author,Price]
pickle.dump(rec,f)
f.close()
(ii)
def CountRec(Author):
f=open("Book.dat","rb")
num = 0
try:
while True:
rec=pickle.load(f)
if Author==rec[2]:
num = num + 1
except:
f.close()
return num
A binary file student.dat has structure A binary file “STUDENT.DAT” has structure
(rollno,name,class,percentage). Write a program (admission_number, Name, Percentage). Write a
to updating a record in the file requires roll function countrec() in Python that would read
number to be fetched from the user whose name contents of the file “STUDENT.DAT” and display
is to be updated the details of those students whose percentage is
import pickle above 75. Also display number of students
import os scoring above 75%
f1 = open(‘student.dat','rb')
f2=open(“temp.dat”,”wb”) import pickle
r=int(input(“enter rollno which you want to def CountRec():
search”)) f=open("STUDENT.DAT","rb")
try: num = 0
while True: try:
e = pickle.load(f1) while True:
if e[0]==r: rec=pickle.load(f)
e*1+=input(“enter name”) if rec[2] > 75:
pickle.dump(e,f2) print(rec[0],rec[1],rec[2])
else: num = num + 1
pickle.dump(e,f2) except:
except: f.close()
f1.close() return num
f2.close()
os.remove(“student.dat”)
os.rename(“temp.dat”,”student,dat”)
A binary file named “EMP.dat” has some records A binary file “Items.dat” has structure as [ Code,
of the structure [EmpNo, EName, Post, Salary] Description, Price ].
(a) Write a user-defined function named i. Write a user defined function MakeFile( ) to
NewEmp() to input the details of a new employee input multiple items from the user and add to
from the user and store it in EMP.dat. Items.dat
(b) Write a user-defined function named ii. Write a function SearchRec(Code) in Python
SumSalary(Post) that will accept an argument the which will accept the code as parameter and
post of employees & read the contents of search and display the details of the
EMP.dat and calculate the SUM of salary of all corresponding code on screen from Items.dat.
employees of that Post. (i)
(a) import pickle
import pickle def MakeFile( ):
def NewEmp ( ): while True:
f = open(“EMP.dat”,”wb”) code = input(“Enter Item Code :”)
EmpNo = int(input(“Enter employee desc = input(“Enter description :”)
number: “)) price = float(input(“Enter price:”))
EName = input(“Enter name:”) d= [code,desc,price]
Post = input(“Enter post:”) f = open (“Items.dat”, “ab”)
Salary = int(input(“Enter salary”)) pickle.dump( d,f )
rec = [EmpNo, Ename, Post,Salary] ch = input(“Add more record? (y/n) :”)
pickle.dump(rec, f) if ch==’n’:
f.close() break
(b) f.close( )
def SumSalary(Post): (ii)
f = open("EMP.dat", "rb") def SearchRec(code):
c=0 f = open("Items.dat", "rb")
while True: found = False
try: while True:
g = p.load(f) try:
if g[2]==Post: g = p.load(f)
c=c+g[3] if g[0]==code:
except: print(g[0],g[1],g[2])
f.close() found=True
print("sum of salary", c) break
except:
if found == False:
print("No such record")
f.close()
A binary file named “TEST.dat” has some records Consider a binary file emp.dat having records in
of the structure [TestId, Subject, MaxMarks, the form of dictionary. E.g {eno:1, name:”Rahul”,
ScoredMarks] Write a function in Python named sal: 5000} write a python function to display the
DisplayAvgMarks(Sub) that will accept a subject records of above file for those employees who
as an argument and read the contents of get salary between 25000 and 30000
TEST.dat. The function will calculate & display the
Average of the ScoredMarks of the passed
Subject on screen.
def SumSalary(Sub): import pickle
f = open("ABC.dat", "rb") def search():
c=0 f=open(“emp.dat”,”rb”)
s=0 while True:
while True: try:
try: d=pickle.load(f)
g = p.load(f) if(d*‘sal’+>=25000 and d*‘sal’+<=30000):
print(g) print(d)
if g[1]==Sub: except EOFError:
s=s+g[3] break
c=c+1 f.close()
except:
f.close()
print("sum of salary", s/c)
f.close()
A binary file “Bank.dat” has structure as Consider an employee data, Empcode, empname
[account_no, cust_name, balance]. and salary.
i. Write a user-defined function addfile( ) and add (i) Write python function to create
a record to Bank.dat. binary file emp.dat and store their
ii. Create a user-defined function CountRec( ) to records.
count and return the number of customers (ii) write function to read and display all
whose balance amount is more than 100000. the records
(i) Ans
import pickle import pickle
def addfile( ): def add_record():
f = open(“bank.dat”,”wb”) f = open(“emp.dat”,”ab”)
acc_no = int(input(“Enter account empcode =int(input(“employee code:”))
number: “)) empname = int(input(“empName:”))
cust_name = input(“Enter name:”) salary = int(input(“salary:”))
bal = int(input(“Enter balance”)) d = [empcode, empname, salary]
rec = [acc_no, cust_name, bal] pickle.dump(d,f)
p.dump(rec, f) f.close()
f.close() import pickle
(ii)
def CountRec( ): def search():
f = open(“bank.dat”,”rb”) f=open(“emp.dat”,”rb”)
c=0 while True:
try: try:
while True: d=pickle.load(f)
rec = p.load(f) print(d)
if rec[2] > 100000: except EOFError:
c += 1 break
except: f.close()
f.close()
return c
Write a function SCOUNT( ) to read the content Given a binary file “emp.dat” has structure
of binary file “NAMES.DAT‟ and display number (Emp_id, Emp_name, Emp_Salary). Write a
of records (each name occupies 20 bytes in file ) function in Python countsal() in Python that
where name begins from “S‟ in it would read contents of the file “emp.dat” and
def SCOUNT( ): display the details of those employee whose
s=' ' salary is greater than 20000
count=0 import pickle
f=open('Names.dat', 'rb'): def countsal():
while True: f = open (“emp.dat”, “rb”)
s = f.read(20) n=0
if len(s)!=0: try:
if s[0].lower()=='s': while True:
count+=1 rec = pickle.load(f)
print('names beginning from "S" are ',count) if rec[2] > 20000:
print(rec[0], rec[1], rec[2])
n=n+1
except:
print(n)
f.close()
Write Python function DISPEMP( ) to read the Consider the following CSV file (emp.csv):
content of file emp.csv and display only those Sl,name,salary
records where salary is 4000 or above 1,Peter,3500
import csv 2,Scott,4000
def DISPEMP(): 3,Harry,5000
csvfile=open('emp.csv'): 4,Michael,2500
myreader = csv.reader(csvfile,delimiter=',') 5,Sam,4200
print(EMPNO,EMP NAME,SALARY) Write Python function DISPEMP( ) to read the
for row in myreader: content of file emp.csv and display only those
if int(row[2])>4000: records where salary is 4000 or above
print(row[0], row[1],row[2]) import csv
def DISPEMP():
csvfile=open('emp.csv'):
myreader = csv.reader(csvfile,delimiter=',')
print(EMPNO,EMP NAME,SALARY)
for row in myreader:
if int(row[2])>4000:
print(row[0], row[1],row[2])
A binary file “Stu.dat” has structure (rollno, A binary file “Stu.dat” has structure (rollno,
name, marks). name, marks).
Write a function in Python add_record() to input Write a function in python Search_record() to
data for a record and add to Stu.dat. search a record from binary file “Stu.dat” on the
import pickle basis of roll number.
def add_record(): def Search_record():
fobj = open(“Stu.dat”,”ab”) f = open(“Stu.dat”, “rb”)
rollno =int(input(“Roll no:”)) stu_rec = pickle.load(f)
name = int(input(“Name:”)) found = 0
marks = int(input(“Marks:”)) rno = int(input(“roll number to search:”))
data = [rollno, name, marks] try:
pickle.dump(data,fobj) for R in stu_rec:
fobj.close() if R[0] == rno:
print (R[1], “Found!”)
found = 1
break
except:
if found == 0:
print (“Sorry, record not found:”)
f.close()
CSV-
#import csv #csv module
#csv module functions ----csv.reader() ,csv.writer()
#writerow()-single record,
#writerows()-multiple records
''' '''
write a python function writecsv () to write the write a python function writecsv () to write the
following information into following information into product.csv.Heading
product.csv. of the product .csv is as follows
pid,pname,cost,quantity pid,pname,cost,quantity
p1,brush,50,200 '''
p2,toothbrush,120,150 def writecsv(pid,pname,cost,quantity):
p3,comb,40,300 f=open("marks.csv","w")
p4,sheets,100,500 r=csv.writer(f,newline="")
p5,pen,10,250 r.writerow([pid,pname,cost,quantity])
''' f.close()
#solution
def writecsv():
f=open("product.csv","w")
r=csv.writer(f,lineterminator='\n')
r.writerow(['pid','pname','cost','qty'])
r.writerow(['p1','brush','50','200'])
r.writerow(['p2','toothbrush','12','150'])
r.writerow(['p3','comb','40','300'])
r.writerow(['p5','pen','10','250'])
f.close()
write a python function readcsv () to display the write a python function readcsv () to display the
following information into following information into
product.csv. assume that following info is already product.csv. assume that following info is already
present in the file. present in the file.
pid,pname,cost,quantity pid,pname,cost,quantity
p1,brush,50,200 p1,brush,50,200
p2,toothbrush,120,150 p2,toothbrush,120,150
p3,comb,40,300 p3,comb,40,300
p4,sheets,100,500 p4,sheets,100,500
p5,pen,10,250 p5,pen,10,250
Ans Ans
import csv import csv
def readcsv(): def readcsv():
f=open("product.csv","r") f=open("product.csv","r")
r=csv.reader(f) r=csv.reader(f)
for i in r: for i in r:
print(i) print(i[0],i[1],i[2],i[3])
f.close() f.close()
AddNewRec(“INDIA”,”NEW DELHI”)
AddNewRec(“CHINA”,”BEIJING”) (e)
ShowRec() # Statement-5 INDIA NEW DELHI
CHINA BEIJING
(a) Name the module to be imported in Statement-1.
(b) Write the file mode to be passed to add new record in
Statement-2.
(c) Fill in the blank in Statement-3 to close the file.
(d) Fill in the blank in Statement-4 to read the data from a csv file.
(e) Write the output which will come after executing Statement-
5.
addCsvFile(“Aman”,”123@456”)
addCsvFile(“Anis”,”aru@nima”)
addCsvFile(“Raju”,”myname@FRD”) (e) Line 5 :
readCsvFile() #Line 5 Aman 123@456
Anis aru@nima
(a) Give Name of the module he should import in Line 1. Raju myname@FRD
(b) In which mode, Aman 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.