A File Is A Sequence of Characters / Data Which Occupies Named Place On The Disk Where A Sequence of Related Data Is Stored
A File Is A Sequence of Characters / Data Which Occupies Named Place On The Disk Where A Sequence of Related Data Is Stored
Three major operation we have to perform on data file : reading, writing and appending.
Three type of data file supported : TEXT FILE & BINARY FILES & CSV FILES.
TEXT FILE BINARY FILE
A text file store information in ASCII or A binary file is just a file contain
Unicode characters. In text files each line of information in the same format in which
text is terminated with a special character the information is held in the memory.. In
– EOL(end of line). binary file there is no delimiter for line.
OPENING & CLOSING THE DATA FILE :
Open() function is used to open a data file. It takes two arguments
1. Name if the file
2. Mode of the file. Always create the file in the same
Syntax : folder where your python has
been installed….
File object = open(filename , access mode)
Eg-
abc=open(“check.txt”,”r”)
abc = open("check.txt")
print("file name is ",abc.name)
print("file mode ",abc.mode)
print("file is readable ",abc.readable())
print("file closed ",abc.closed)
abc.close()
print("file closed ",abc.closed)
READING DATA FROM THE FILE
read() Reads at most n bytes from the file, if n is not given then reads the entire file.
readline() Reads a line of input, if n is specified reads at most n bytes.
readlines() Read all the lines and return them in a list
abc = open("check.txt")
#pr=abc.read()
#print("Reading and Printining entire data file - check.txt")
#print(pr)
r = abc.read(15)
print("printing first 15 characters : ",r)
abc.close()
abc = open("english.txt",'w')
abc.write("describing data file handling concepts \n")
abc.close()
NOTEPAD FILE : english.txt
Appending data to
abc = open("english.txt",'a') the text file using
abc.write("this topic is for class xii \n") file mode – ‘a’
abc.close()
NOTEPAD FILE : english.txt
abc = open("english.txt",'w') EXAMPLE OF writelines()
s="this is my book of cs. \nthis is for class xii"
abc.writelines(s)
abc.close()
abc = open("book.txt",'w')
l=['cs\n','java\n','python\n','mysql\n']
abc.writelines(l)
abc.close()
WAP TO OBTAIN ROLL NO, NAME AND MARKS OF THREE STUDENTS AND
THEN STORE IS DATA IN A TEXT FILE.
xyz=open("student_data.txt","w") INPUT TEXT FILE
for i in range(1,4):
rno = int(input("enter rollno "))
name = input("enter name ")
marks = int(input("enter marks "))
xyz.write(str(rno))
xyz.write(name)
xyz.write(str(marks))
xyz.write("\n")
xyz.close()
xyz=open("computer.txt","r") xyz=open("computer.txt","r")
pr = xyz.read() pr = xyz.read()
k=pr.split() c=0
c=0 for i in pr:
print(k) if i==' ':
for i in k: c=c+1
c=c+1 print("no of words ",c+1)
print("no of words ",c) xyz.close()
xyz.close()
xyz=open("check.txt","r")
pr = xyz.readlines() NOTEPAD FILE : CHECK.TXT
c=0
for i in pr:
if i[0]=="P":
print(i)
c=c+1
print("number of line starting from P ",c)
xyz.close()
WAP TO OTAIN CHARACTERS FROM THE USER TILL USER ENTER “-1” AND STORE
ALL CAPIATL CHARCTERS TO “UPPER.TXT”, SMALL LETTERS TO “LOWER.TXT”,
DIGITS TO “DIGITS.TXT” AND OTHER CHARACTERS TO “OTHERS.TXT”
up=open("upper.txt","w")
lw=open("lower.txt","w")
ot=open("others.txt","w")
dg=open("digits.txt","w")
while True:
s=input("enter a character ")
if s== "-1":
break
if s.isupper():
up.write(s)
elif s.islower():
lw.write(s)
elif s.isdigit():
dg.write(s)
else:
ot.write(s)
lw.close()
dg.close()
ot.close()
up.close()
WAP TO DISPLAY THE LAST LINE OF THE TEXT FILE
CHECK.TXT
xyz=open("check.txt","r")
pr = xyz.readlines()
print("last line of the file ")
print(pr[-1])
xyz.close()
def fun1():
abc=open("check.txt")
f=abc.read()
m=f.split()
c=0
for i in m:
if i=="me" or i=="my":
c=c+1
print("total me and my ",c)
abc.close()
fun1()
WAP TO DISPLAY ALL THE LINES FROM THE FILE
WHICH CONTAIN PYTHON COMMENT CHARACTER “#”
abc=open("hash.txt","r")
pr=abc.readlines()
for i in pr:
l=len(i)
for j in range(l):
if i[j]=="#":
print(i)
abc.close()
import pickle
st=[] import pickle
ch='y' f=open("st_data.dat","rb+")
while ch=='y': stu=pickle.load(f)
rno=int(input("enter roll num ")) for i in stu:
name=input("enter name ") print(i)
marks = int(input("enter marks ")) f.close()
s=[rno,name,marks]
File operations ?
st.append(s) 1. Creation / adding a record
ch=input("want to add more ") 2. Display all rec
3. Searching
f=open("st_data.dat","wb") 4. Modify / update
pickle.dump(st,f) 5. Delete
f.close()
PROJECT
SEARCHING DATA IN A UPDATING DATA IN A BINARY FILE
BINARY FILE import pickle
f=open("st_data.dat ","rb+")
import pickle
stu=pickle.load(f)
f=open("st_data.dat","rb")
n=int(input("enter roll number to be update "))
stu=pickle.load(f) for i in stu:
r=int(input("roll numbe ")) s=i[0]
else: else:
print("rec not found")
print("rec not found")
f.seek(0) “will move the file pointer to the first record”
f.close()
pickle.dump(stu,f)
f.close()
CREATING A BINARY FILE :
ADDING RECORDS IN A BINARY READING DATA FROM THE
FILE USING A DICTIONARY BINARY FILE : AS A DICTIONARY
import pickle
import pickle
f=open("maps.dat","ab")
f=open("maps.dat","rb")
ch="y"
d={}
while ch == "y":
try:
r=int(input("input enter rno "))
while True:
s=input("enter name ")
d=pickle.load(f)
m=int(input("input enter marks "))
print(d)
l2={"rno":r,"name":s,"MARKS":m}
except EOFError:
pickle.dump(l2,f)
f.close()
ch=input("want to enter more rec ")
f.close()
Deletion logic
DELETION IN A BINARY FILE
def bumper():
import pickle
f=open("gifts.dat","rb")
cont=pickle.load(f)
c=0
print("details of gifts having remarks as - on discount")
for i in cont:
if i[2]=="on discount":
c=1
print(i)
f.close()
if c==0:
print(“rec not found”)
bumper()
Ques2-Following is the structure of each record in a data file named ”PRODUCT.DAT”.
[CODE, DESC,VALUE] The values for prod_code and prod_desc are strings, and the value for stock is an integer.
Write a function in PYTHON to update the file with a new value of stock. The product_code, whose DESC AND
STOCK VALUE is to be updated, is to be input during the execution of the function
import pickle def fun(n,d,s):
st=[] import pickle
ch="y" f=open("product.dat","rb+")
while ch=="y": cont=pickle.load(f)
pcode=input("enter product code=") for i in cont:
desc=input("enter desc of product=") if i[0]==n:
value=int(input("enter value=")) i[1]=d
s=[pcode,desc,value] i[2]=s
st.append(s) f.seek(0)
ch=input("do you want to cont(y/n)=") pickle.dump(cont,f)
f=open("product.dat","wb") f.close()
pickle.dump(st,f) a=input("enter product code to be updated")
f.close() desc=input("enter new desc=")
stock=int(input("enter new stock value="))
fun(a,desc,stock)
Write a function in PYTHON to search for a laptop from a binary file “LAPTOP.DAT” containing the records of following
type. The user should enter the model number and the function should display the details of the laptop.
[ModelNo, RAM, HDD, Details] where ModelNo, RAM, HDD are integers, and Details is a string.
import pickle def search(m):
file=open('LAPTOP.dat','wb') file=open('LAPTOP.dat','rb+')
ch='y' data=pickle.load(file)
l=[]
for i in data:
while ch=='y':
model_no=int(input('enter the model no-')) if i[0]==m:
ram=int(input('enter the ram-')) print('record found!')
hdd=int(input('enter the hdd-')) print('MODEL NO-',i[0])
details=input('enter the details-') print('RAM-',i[1])
s=[model_no,ram,hdd,details] print('HDD-',i[2])
l.append(s) print('DETAILS-',i[3])
print('record added!')
break
ch=input('do you want to continue(y/n)-')
pickle.dump(l,file) if i[0]!=m:
file.close() print('record not found!')
file.close()
m=int(input('enter the model no. of the laptop-'))
search(m)
REVISION OF TEXT FILE :
WAP TO READ AND DISPLAY THOSE LINE WHICH STARTS WITH ALPHABET A IN THE FILE “BOOK.TXT”.
Wap to obtain string from the user and then transfer all vowels to vowels.txt, numbers to digits.txt
and all other characters to other.txt.
Abc=open(“student.dat”,”r”)