File Handling 2022 - Complete Notes
File Handling 2022 - Complete Notes
INTRODUCTION
Text file
Binary file
CSV file
TYPES OF FILE
OPEN A FILE
• Python‟s built-in open() function
−It is used to open a file and return a file object .
−File objects contain methods and attributes about the file
− open() is most commonly used with two arguments
−Syntax:- file_object_name = open(filename, mode)
• The first argument is the filename
– Example :- f=open(“intro.txt")
– file extension is .txt
– Python looks in the current directory for the file
• The second argument is the file access mode
FILE ACCESS MODES
OPEN A FILE
def count_the():
f=open(“demo.txt",'r')
c=0
a=f.read() # read all content and store in string
b=a.split() # split the string into words
for i in b: # iterate through all words one by one
if i.lower()=="the": # condition
c=c+1 # increment /display
print("No of The word =",c)
f.close() #close the file
READING CHARACTERS FROM A LINE
myobject=open("myfile.txt",'r')
d=myobject.readlines()
for line in d:
words=line.split()
print(words)
O/P:
2 WAYS OF WRITING TO A TEXT FILE
fobject=open("text_file3.txt","w")
sentence=input("Enter the contents to be written in
the file: ")
fobject.write(sentence)
fobject.close()
print("Now reading the contents of the file: ")
fobject=open("testfile.txt","r")
for str in fobject:
print(str)
fobject.close()
OUTPUT
EX: Entering student name to the text file using write() with “w”
mode:
myfile = open("book.txt","a")
ans='y'
while ans=='y':
book_no=int(input("Enter Book Number: "))
book_name=input("Enter Book Name: ")
author=input("Enter Author Name: ")
price=int(input("Enter Book Price: "))
book_record=str(book_no)+","+book_name+","+author+","+str(price)+'\n'
myfile.write(book_record)
ans=input("Want to add more data ?")
myfile.close()
print("Data Added Successfully....")
EX- TO COPY DATA FROM ONE FILE TO ANOTHER FILE
import sys
sys.stdout.write("enter number to be checked") # output on screen
a=int(sys.stdin.read(2)) # read from keyboard
for i in range(2,a):
if a%i==0:
sys.stdout.write("not a prime") # output on screen
break
else:
sys.stderr.write("prime") # output in red color
BASIC OPERATIONS ON A BINARY
FILE
• binary file is also opened and closed in same way as text file by open() function
and close() function respectively but extension of file is .dat and mode of opening
binary file is given below:
Syntax:- file_object=open('data.dat', 'wb')
PICKLE
File_object = open(“file_name.dat”,”wb”)
Ex: Program to get student details from user and wirte input data to the binary file.
import pickle
stud = { }
fh = open("stud.dat","wb")
ans='y'
while ans=='y':
roll = int(input("Enter roll no.: "))
name = input("Enter name: ")
percent = int(input("Enter percentage of marks: "))
stud["Roll no."] = roll
stud["Namee"]= name
stud["percentage"]=percent
pickle.dump(stud, fh)
ans=input("want to enter more record press: y else n: ")
fh.close()
EX: write
a program to write employee data to the binary file
named emp.dat from the dictionary
import pickle
emp1={"Emp_no":101, "Name":'Anushka', 'Age':28, 'Salary':52000}
emp2={"Emp_no":102, "Name":'Virat', 'Age':29, 'Salary':72000}
emp3={"Emp_no":103, "Name":'Manshi', 'Age':24, 'Salary':43000}
emp4={"Emp_no":104, "Name":'Ankit', 'Age':26, 'Salary':29000}
emp5={"Emp_no":105, "Name":'Vijay', 'Age':29, 'Salary':46000}
fh = open("emp.dat","wb")
pickle.dump(emp1,fh)
pickle.dump(emp2,fh)
pickle.dump(emp3,fh)
pickle.dump(emp4,fh)
pickle.dump(emp5,fh)
except EOFError:
fh.close()
APPEND INTO BINARY FILE
import pickle
stud={}
fob = open("stud.dat","ab")
ans='y'
while ans=='y':
roll = int(input("Enter roll no.: "))
name = input("Enter name: ")
percent = int(input("Enter percentage of marks: "))
stud["Roll no."] = roll
stud["Name"]= name
stud["percentage"]=percent
#write into the file
pickle.dump(stud, fob)
ans=input("want to enter more record press: y else n: ")
fob.close()
READ FROM A BINARY FILE
AFTER APPENDING DATA
except EOFError:
fh.close()
# program to search student with roll no.
import pickle
stud ={} SEARCH IN BINARY FILE
file = open("stud.dat","rb")
search_roll = int(input("Enter roll no. to be search: "))
found = False
#read data from the stud.dat file
try:
print("Seraching in file stud.dat....")
while True:
stud = pickle.load(file)
if stud["Roll no."] == search_roll:
print(stud)
found = True
except EOFError:
if found==False:
print("No such record found in the file.")
else:
print("Search successful.")
# program to search student who got more than 85 %
import pickle
stud={ } SEARCH STUDENT % > 85
found = False
print("Searching in Stud.dat file...")
#open stud.dat file in read mode
fh = open("stud.dat","rb")
try:
while True:
stud=pickle.load(fh)
if stud["percentage"]>85:
print(stud)
found=True
except EOFError:
if found == False:
print("No such student found...")
else:
print("search scuccessful.")
fh.close()
# program to update the marks of student who got less than 85 by 2.
import pickle
stud ={} UPDATE DATA IN BINARY FILE
found =False
#open stud.dat file in read and write mode.
fh = open("stud.dat","rb+")
try:
while True:
f_pointer = fh.tell()
stud = pickle.load(fh)
if stud["percentage"]< 85:
stud["percentage"]= stud["percentage"] + 2
fh.seek(f_pointer)
pickle.dump(stud,fh)
found = True
except EOFError:
if found == False:
print("No such student found.")
else:
print("Record(s) successfully updated.")
fh.close()
# program to modify the name of student whose roll no. is 05 by Arman.
import pickle
stud ={}
found =False UPDATE DATA IN BINARY FILE
fh = open("stud.dat","rb+")
try:
while True:
f_pointer = fh.tell()
stud = pickle.load(fh)
if stud["Roll no."] == 5:
stud["Name"]= "Arman"
fh.seek(f_pointer)
pickle.dump(stud,fh)
found = True
except EOFError:
if found == False:
print("No such record found.")
else:
print("Record(s) successfully updated.")
fh.close()
CSV MODULE
Ex 1 – Write a program to create a csv file to store student data , take data
from user and write record into it.
import csv
fh = open("student.csv","w")
stud_writer = csv.writer(fh)
header=["Roll_no", "Name", "Marks"]
stud_writer.writerow(header)
for i in range(5):
print("Enter Student " + str(i+1) +" Data: ")
roll = int(input("Enter Roll_no: "))
name = input("Enter Student's Name: ")
marks = float(input("Enter Marks in CS: "))
stud_rcd = [roll,name,marks]
stud_writer.writerow(stud_rcd)
fh.close()
WRITE DATA INTO CSV FILE USING
writerows( )
Ex 1 – Write a program to create a csv file to store student data ,
using list of records.
import csv
fh = open("student1.csv","w")
writer = csv.writer(fh)
stud_data = [ ["Roll","Name","Marks"],
[1,"Aditya",95],
[2,"Vishnu",96],
[3,"Anushka",89],
[4,"Virat",85],
[5,"Rahul",94]
]
writer.writerows(stud_data)
fh.close()
print("Data written successfully...")
READ FROM CSV FILE