0% found this document useful (0 votes)
45 views48 pages

A File Is A Sequence of Characters / Data Which Occupies Named Place On The Disk Where A Sequence of Related Data Is Stored

Uploaded by

LAKSHAY AGGARWAL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views48 pages

A File Is A Sequence of Characters / Data Which Occupies Named Place On The Disk Where A Sequence of Related Data Is Stored

Uploaded by

LAKSHAY AGGARWAL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

DATA FILE HANDLING

A file is a sequence of characters / data which occupies named


place on the disk where a sequence of related data is stored.
Data file operation
1. Opening a file.
2. Performing operations(read, write)
3. Closing the file.

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”)

FILE OBJECT FILE NAME FILE MODE

We can skip file mode from the open(0 as it is an optional parameter ,


then file is opened in read mode by default
Close() function is used to flushes any unwritten information and closes the
file object , after which no more writing can be done. Syntax -
file_object.close()
FILE MODES
VARIOUS METHODS RELATED TO THE FILE OBJECT
Name : name of the file opened
Mode : mode in which file is opened
Closed : returns Boolean value (true/false) which indicates the file is closed or not.
Readable : returns Boolean value which indicate file is readable or not.

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()

NOTEPAD FILE : CHECK.TXT


Example of readline() Example of readlines()
abc = open("check.txt") abc = open("check.txt")
pr=abc.readline() pr=abc.readlines()
print("printing first line of the text file :- “) for i in pr:
Print( pr) print(i,end="")
abc.close() abc.close()

•First call of the function will return the first


line and so on
•Line is terminated by \n.
NOTEPAD FILE : CHECK.TXT
Another way to read
entire data from the file
abc = open("check.txt")
for i in abc:
print(i,end="")
abc.close()
WRITING DATA TO FILE file mode ‘w’
write() Write string to the file. We have to add \n char. To store data in separated lines.
writelines() Write function can not be used to write list, tuple etc. sequence of data including
string can be written using writeline()

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()

NOTEPAD FILE : english.txt

Writing a list in a text file NOTEPAD FILE : book.txt

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()

PROGRAM TO READ THE CONTENT OF TEXT FILE


xyz=open("student_data.txt","r")
pr = xyz.readlines()
for i in pr:
print(i,end="")
xyz.close()
WAP TO COUNT AND DISPLAY THE NUMBER OF
CAPITAL VOWELS IN A FILE CHECK.TXT
xyz=open("check.txt","r")
pr = xyz.read()
c=0
for i in pr:
if i in "AEIOU":
c=c+1
print("NUMBER OF CAPITAL VOWELS IN THE TEXT FILE ",c)
xyz.close()

NOTEPAD FILE : CHECK.TXT


WAP TO COUNT AND DISPLAY THE NUMBER OF
SPACES IN A TEXT FILE COMPUTER.TXT
xyz=open("computer.txt","r")
pr = xyz.read()
c=0
for i in pr:
if i==' ':
c=c+1
print("NUMBER OF SPAES IN TEXT FILE ",c)
xyz.close() NOTEPAD FILE : COMPUTER.TXT
WAP TO COUNT AND DISPLAY THE NUMBER OF
SPECIAL CHARCTER IN A TEXT FILE COMPUTER.TXT
xyz=open("computer.txt","r")
pr = xyz.read()
c=0
for i in pr:
if i.isalnum()== False:
c=c+1
print("NUMBER OF SPECIAL CHARACTER IN TEXT FILE - ",c)
xyz.close() NOTEPAD FILE : COMPUTER.TXT
WAP TO COUNT THE NUMBER OF
WORDS IN A TEXT FILE COMPUTER.TXT
(2 WAYS OF DOING SAME PROGRAM)

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()

NOTEPAD FILE : COMPUTER.TXT


WAP TO DISPLAY AND WAF TO DISPLAY AND RETURN THE
NUMBER OF
COUNT THE NUMBER OF WORDS IN A TEXT FILE WHICH ARE
WORDS IN A TEXT FILE STARTING FROM “T”
WHICH ARE STARTING def fun1():
FROM “T” xyz=open("check.txt","r")
pr = xyz.read()
c=0
xyz=open("check.txt","r") w=pr.split()
pr = xyz.read() for i in w:
c=0 if i[0]=="t":
w=pr.split() print(i)
for i in w: c=c+1
if i[0]=="T": xyz.close()
print(i) return c
c=c+1 R=Fun1()
print(c) Print( r)
xyz.close() NOTEPAD FILE : CHECK.TXT
WAP TO COPY DATA FROM FILE “CHECK.TXT” TO
“CHECK1.TXT” AFTER CONVERTING THE CHARACTERS
TO TOGGLE CASE.
xyz=open("check.txt","r")
abc=open("check1.txt","w")
pr = xyz.read()
NOTEPAD FILE : CHECK.TXT
for i in pr:
if i.isupper():
i=i.lower()
elif i.islower(): NOTEPAD FILE : CHECK1.TXT
i=i.upper()
print(i,end="")
abc.write(i)
xyz.close()
abc.close()
WAP TO DISPLAY AND COUNT THE NUMBER OF
LINES IN A TEXT FILE WHICH ARE STARTING FROM “P”

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()

NOTEPAD FILE : CHECK.TXT


'''waf to count number of me and my
in a text file'''

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()

NOTEPAD FILE : HASH.TXT


WAP TO DISPLAY ALL THE WORDS ENDING WITH “M” IN
THE TEXT FILE “CHECK.TXT”
abc=open("check.txt","r")
pr=abc.read()
w=pr.split()
for i in w:
if i[-1]=="m":
print(i)
abc.close()
NOTEPAD FILE : CHECK.TXT
WAP TO DISPLAY ALL THE WORDS HAVING LENGTH
LESS THAN 4 ALSO COUNT THESE WORDS.
abc=open("check.txt","r")
pr=abc.read()
w=pr.split()
c=0
for i in w:
if len(i)<4:
print(i)
c=c+1 NOTEPAD FILE : CHECK.TXT
print("total number of words ",c)
abc.close()
WAP to obtain 2 numbers from the user and then display the square Of the maximum
number and also store all the three numbers in a text file Max_num.txt.
Also write another program to read and display the content of max_num.txt file.

n= int(input(“num1 “)) xyz=open(“max_num.txt","r")


m=int(input(“num2 “)) pr = xyz.readlines()
if n>m: for i in pr:
print(i)
s=n*n
xyz.close()
else:
s=m*m
abc=open(“max_num.txt”,”w”)
abc.write(str(n))
abc.write(str(m))
abc.write(str(s))
abc.close()
CREATING A BINARY FILE :
ADDING RECORDS READING DATA FROM THE
IN A BINARY FILE USING A LIST BINARY FILE : AS A LIST

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]

for i in stu: if s==n:


print("record found ")
if i[0]==r:
i[1]=input("enter name ")
print("rec found")
i[2]=int(input("enter marks "))
print(i[1],":",i[2]) print("record update")
break break

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

import pickle Copy the records other than the


f=open("st_data.dat","rb+") Record to be deleted in a list and
d=[] then dump this
stu=pickle.load(f) List in a file
n=int(input("enter roll number to be delete "))
for i in stu: File1.dat list
s=i[0] 1 1
if s!=n: 2 2
print("record found ") 3 this is to left out
d1=[i[0],i[1],i[2]] 4 4
d.append(d1) 5 5
print("record deleted")
else: Rec = 3 to be deleted
print("rec not found")
f.seek(0)
pickle.dump(d,f)
f.close()
WRITING DATA TO CSV FILE READING DATA FROM CSV FILE
Ques1-Write a definition for function BUMPER() in PYTHON to read each object of a binary file GIFTS.DAT, find and
display details of those gifts, which have remarks as “ON DISCOUNT”. Assume that the file GIFTS.DAT is created
with the help of lists of following type: (ID, Gift, Remarks, Price)

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”)

With open(“student.dat”,”r”) as abc

You might also like