0% found this document useful (0 votes)
14 views114 pages

12 Text and Binary File

Uploaded by

shashwatk862
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)
14 views114 pages

12 Text and Binary File

Uploaded by

shashwatk862
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/ 114

File Handling

in Python
x=open(“Smahi.txt”, “w”)

A file memory x created in RAM,


and get connected to a file called
“Smahi.txt” in overwrite mode,
which is available in same folder, if
the file not found, it will be created
automatically.
x=open(“Smahi.txt”,“w”)
x.write(“Debanshi ” )

A file memory x created in RAM,


and get connected to a file called
“Smahi.txt”, in overwrite mode,
which is available in same folder, if
the file not found, it will be created
automatically. A string called
“Debanshi ” is written in file
memory.
x=open(“Smahi.txt”, “w”)
x.write(“Debanshi ”)
x.close()
A file memory x created in RAM,
and get connected to a file called
“Smahi.txt”, which is available in
same folder, if the file not found, it
will be created automatically. A
string called “Debanshi ” is written
in file memory. Now to transfer the
contents of the file memory to the
file “Smahi.txt” we have to
x=open(“Smahi.txt”, “w”)
y=“Debanshi ”
x.write(y)
x.close()
A string variable y is created
and initialized with “Debanshi
”, after that the same is
written in file memory x from
which the contents is
transferred to the file
x=open(“Smahi.txt”, “w”)
y=“Debanshi ”
x.write(y)
x.close()

Remember we
can store only
string in file
x=open(“Smahi.txt”, “w”)
y=23759
x.write(y)
x.close()

Argument of
write() must be
str not int.
x=open(“Smahi.txt”, “w”)
x.write(“Debanshi ”)
x.write(“Sampurna ”)
x.close()

Output:

Debanshi
Sampurna
x=open(“Smahi.txt”, “w”)
x.write(“Debanshi \n”)
x.write(“Sampurna ”)
x.close()

Output:
Debanshi
Sampurna
x=open(“Smahi.txt”, “w”)
x.write(“Debanshi \t”)
x.write(“Sampurna ”)
x.close()

Output:
Debanshi Sampurna
x=open(“Smahi.txt”, “w”)
x.writelines(“Debanshi ”)
x.writelines(“Sampurna ”)
x.close()

Another technique
to write in a file
x=open(“Smahi.txt”, “w”)
x.writelines(“Debanshi ”)
x.writelines(“Sampurna ”)
x.close()

Output:
Debanshi Sampurna
x=open(“Smahi.txt”, “w”)
x.writelines(“Debanshi \n”)
x.writelines(“Sampurna ”)
x.close()

Output in a file:
Debanshi
Sampurna
x=open("Smahi.txt","w")
y=["Debanshi","Sampurna","
Riya"]
x.write(y)
x.close()

Argument in write
must be string, not
list
x=open("Smahi.txt","w")
y=["Debanshi","Sampurna","
Riya"]
x.writelines(y)
x.close()

Its Okay, Output


will be
Debanshi Sampurna Riya
write() is used to
write string,
whereas
writelines() is
used to write list
x=open("Smahi.txt","w")
for y in range(4):
x.write(input("Enter name
"))
x.close()

Program will
accept 4 names
and store in a file
called “Smahi.txt”
x=open("Smahi.txt","w")
for y in range(4):
x.write(input("Enter name
")+‘\n’)
x.close()

Program will accept


4 names and store in
a file in separate
lines, called
x=open("Smahi.txt","w")
for y in range(4):
x.write(input("Enter name
")+‘\n’)
x.close()

Program will accept


4 names and store in
a file in separate
lines, called
x=open("Smahi.txt","w")
z=[]
for y in range(4):
z.append(input("Enter name
")+'\n')
x.writelines(z)
x.close()

Program will accept 4


names and store in a file
in separate lines, called
x=open("Smahi.txt","w")
z=[]
for y in range(4):
z[y].append(input("Enter name ")
+'\n')
x.writelines(z)
x.close()

Error:
Instead of z[y], we have
to write z
x=open("Smahi.txt","w")
z=[]
for y in range(4):
z.append(input("Enter name ")+'\
n')
x.write(z)
x.close()

Error:
write() is used to input
string not the list
w is used to
create the file in
overwrite mode,
whereas a is
used to create
the file in
x=open("Smahi.txt","a")
z=[]
for y in range(4):
z.append(input("Enter name
")+'\n')
x.writelines(z)
x.close()
Initially if the file contains
Amit
Sumit
New names will be added
after Sumit
x=open("Smahi.txt","a")
z=[]
for y in range(4):
z.append(input("Enter name
")+'\n')
x.writelines(z)
x.close()
Initially if the file
contains nothing, New
names will be added from
beginning of the file
Reading from a
file
Let the contents of the file
Smahi.txt is
Ram
Shyam
x=open("Smahi.txt",“r")
y=x.read()
print(y)
x.close()
Output:
Ram
Shyam
Warning
If the file we are
trying to open for
reading is not
present in the disk,
in that case it will
Let the contents of the file
Smahi.txt is
Ram
Shyam
x=open("Smahi.txt",“r")
y=x.read(2)
print(y)
x.close()

Output:
Ra
Let the contents of the file
Smahi.txt is
Ram
Shyam
x=open("Smahi.txt",“r")
y=x.read(3)
print(y)
x.close()

Output:
Ram
Let the contents of the file
Smahi.txt is
Ram
Shyam
x=open("Smahi.txt",“r")
y=x.read(4)
print(y)
x.close()

Output:
Ram
Let the contents of the file
Smahi.txt is
Ram
Shyam
x=open("Smahi.txt",“r")
y=x.read(5)
print(y)
x.close()

Output:
Ram
S
Let the contents of the file
Smahi.txt is
Ram
x=open("Smahi.txt",“
Shyam
r")
y=x.read(3)
print(y)
y=x.read(5)
print(y)
Output:
x.close()
Ram

Shya
x=open("Smahi.txt
",“r")
y=x.read(3)

Here data type of


y will be string
Let the contents of the file
Smahi.txt is
Ram
Shyam
x=open("Smahi.txt",“
Ajay
r")
y=x.readline()
print(y)
x.close()
Output:
Ram
Let the contents of the file
Smahi.txt is
Ram
Shyam
x=open("Smahi.txt",“
Ajay
r")
y=x.readline(2)
print(y)
x.close()
Output:
Ra
Let the contents of the file
Smahi.txt is
Ram
Shyam
x=open("Smahi.txt",“
Ajay
r")
y=x.readline()
print(y)
y=x.readline() Output:
Ram
print(y)
x.close() Shyam
“r")
y=x.readline()
Here data
type of y is
string
Let the contents of the file
Smahi.txt is
Ram
Shyam
x=open("Smahi.txt",“
Ajay
r")
y=x.readlines()
print(y)
x.close()
Output:
['Ram\n','Shyam\
n’,]
Let the contents of the file
Smahi.txt is
Ram
Shyam
x=open("Smahi.txt",“
Ajay
r")
y=x.readlines()
print(y)
x.close()
Output:
['Ram\n', 'Shyam\n’,
‘Ajay\n’]
“r")
y=x.readlines()
Here data
type of y is
list
x=open("Smahi.txt")
for y in x:
print(y)
x.close()
output
Ram
Shyam
Ajay
x=open("Smahi.txt")
for y in x:
print(y)
x.close()
output
Here y is working Ram
like read or readline
Shyam
????????............ Ajay
for y in x: 1
print(y)
Shyam
print(z) 2
z=z+1
Ajay
x.close() 3

its working like

readline
opened file can be
closed
automatically
after accepting
data from the file
no need of using
close( )
with open("Smahi.txt")
as x:
y=x.read()
print(y)
output
Ram
Shyam
Ajay
with open("Smahi.txt")
as x:
y=x.read()
print(y[0])
output
R
with open("Smahi.txt")
as x:
y=x.read()
print(type(y))
output
str
while writing in
a file
with open(“Smahi.txt” ,
“w”) as x:
x.write(“Hello
Sampurna”)
x=open("Smahi.txt","w")
y=[ ]
a=int(input("Enter total
number"))
for z in range(a):
y.append(input(“Number ")
+"\n")
x.writelines(y)
x.close()
x=open("Smahi.txt","r")
y=x.readlines()
m=0
z=0
while z<len(y):
print(int(y[z]),end=' ')
if int(y[z])>m:
m=int(y[z])
z=z+1
print("Largest number is ",m)
x.close()
x=open("Smahi.txt","r")
y=x.readlines()
m=0
z=0
print("Entered number was \
n")
while z<len(y):
print(int(y[z]),end=' ')
m=m+int(y[z])
z=z+1
print("\nSum is ",m)
x.close()
y=x.readlines()
m,z=0,0
print("Entered number was \
n")
while z<len(y):
print(int(y[z]),end=' ')
if int(y[z])%2==0:
m=m+1
z=z+1
print("Total even numbers
are", m)
x.close()
y=x.readlines()
m,z=0,0
print("Entered number was \
n")
while z<len(y):
print(int(y[z]),end=' ')
if int(y[z])%2!=0:
m=m+1
z=z+1
print("Total odd numbers
are", m)
x.close()
Contents of mahi1 before
modification is:
Raj
Shayam
Raj
Ajay
Rajeev
Raj
Shayam
Raj
Ajay
Rajeev
Modification in Text
File
y=open("mahi1.txt")
x=y.read()
print(x)
y.close()
y=open("mahi1.txt","w")
x=x.replace("Raj\n","Sanjay\n")
y.write(x)
y.close()
y=open("mahi1.txt")
x=y.read()
print(x)
y.close()
Contents of mahi1
after modification is:
Sanjay
Shayam
Sanjay
Ajay
Rajeev
Sanjay
Shayam
Sanjay
Ajay
Rajeev
Contents of mahi
before
modification is:
Johny Johny yes papa
Eating sugar no papa
Telling lies no papa
Open your mouth Ha
Ha Ha
import os
y=open("mahi.txt")
for x in y:
print(x,end='')
y.close()
y=open("mahi.txt")
z=open("mahidup.txt","w")
for x in y:
m=''
x=x.split()
for t in range(len(x)):
if x[t]=="papa":
x[t]="mummy"
m=m+x[t]+' '
z.writelines(m+'\n')
y.close()
z.close()
os.remove("mahi.txt")
os.rename("mahidup.txt","mahi.txt")
y=open("mahi.txt")
for x in y:
print(x,end='')
y.close()
modification is:
Johny Johny yes
mummy
Eating sugar no
mummy
Telling lies no mummy
Open your mouth Ha
Ha Ha
BINARY
FILES
A binary file is a
computer file that
is not a text file.
The term “binary
file” is often used
as a term meaning

“Non text file”


Generally a binary
file is created to
store list, tuples,
dictionaries and
nested list.
In Binary files 1 st

the data are


serialized and
then stored.
Serialization is the
process in which the
list, tuples and the
dictionaries are
converted into byte
stream and then
stored in the file
Pickling converts an
object in byte stream
in such a way that it
can be reconstructed
in original form when
un - pickled or de -
serialized
In order to work
with pickle
module, we must
1 import it using
st

syntax
import pickle
In pickle module
there are two
functions dump()
and load(), 1 one is
st

used to store the


data in file and the
2 is used to access
nd

data from the file


import pickle
emp1={'name':"amit", "age":23}
emp2={'name':"sumit",
"age":38}
emp3={'name':"ajay", "age":18}
em=open("emp.dat","wb")
pickle.dump(emp1,em)
pickle.dump(emp2,em)
pickle.dump(emp3,em)
print("Data dumped-written in
file.... ")
em.close()
Accessing data from binary
file
import pickle
emp={}
em=open("emp.dat","rb")
try:
while True:
emp=pickle.load(em)
print(emp)
except EOFError:
em.close()
file
import pickle
emp={}
em=open("emp.dat","rb")
print("Name Age")
try:
while True:
emp=pickle.load(em)
print(emp['name'],'\
t',emp['age'])
except EOFError:
em.close()
Accessing selected data from binary file
import pickle
emp={ }
em=open("emp.dat","rb")
m=0
print("Name Age")
try:
while True:
emp=pickle.load(em)
if emp['age']>m:
m=emp['age']
n=emp['name']
except EOFError:
em.close()
print(n, m)
tell(
)
Let the content of the file Smahi.txt
is : -
Ram
Shyam
Ajay
Manoj
Rajeev

x=open("Smahi.txt")
y=x.tell()
print(y) Output
0
Let the content of the file Smahi.txt
is : -
Ram
Shyam
Ajay
Manoj
Rajeev
x=open("Smahi.txt") Output
y=x.tell()
print(y) 0
z=x.read(2)
y=x.tell()
print(y) 2
Smahi.txt is : -
Ram
Shyam
Ajay
Manoj
Rajeev

x=open("Smahi.txt")
z=x.read()
y=x.tell()
OUTPUT
print(y) 33
Smahi.txt is : -
Ram
Shyam
Ajay
Manoj
Rajeev

x=open("Smahi.txt")
z=x.readline()
y=x.tell()
OUTPUT
print(y) 5
Smahi.txt is : -
Ram
Shyam
Ajay
Manoj
Rajeev

x=open("Smahi.txt")
z=x.readline()
z=x.readline()
y=x.tell()
OUTPUT
print(y) 12
Smahi.txt is : -
Ram
Shyam
Ajay
Manoj
Rajeev

x=open("Smahi.txt")
z=x.readline()
z=x.readline()
y=x.tell()
OUTPUT
print(y) 12
seek(
)
Smahi.txt is : -
Ram
Shyam
Ajay
Manoj
Rajeev
x=open("Smahi.txt")
OUTPUT
y=x.tell() 0
print(y) 2
x.seek(2)
y=x.tell()
print(y)
Let the content of the file
Smahi.txt is : -
Ram
Shyam
Ajay
x=open("Smahi.txt") Manoj
y=x.tell() Rajeev
print(y)
x.seek(12) OUTPUT
z=x.read(5) 0
print(z) Ajay
y=x.tell()
print(y) 18
Let the content of the Ram
file Smahi.txt is : - Shyam

Ajay
x=open("Smahi.txt") Manoj
y=x.tell() OUTPUT Rajeev
print(y) 0
x.seek(12)
z=x.read(6)
print(z) Ajay
y=x.tell()
print(y) 19
Smahi.txt is : -
Ram
Shyam
Ajay
x=open("Smahi.txt") Manoj
y=x.tell() Rajeev
print(y)
m=x.read(8)
OUTPUT
print(m) ERROR
x.seek(-5) indexing is
y=x.tell() always
print(y) positive
Smahi.txt is : -
Ram
x=open("Smahi.txt") Shyam
x.seek(12) Ajay
print(x.tell()) Manoj
x.seek(-5,2) Rajeev
print(x.tell())
x.close()

Error: - Cursor movement is


allowed from beginning of the file
only. Then how to move the cursor
from any where ?????
Open the
text file in
binary
mode
Let the content of the file
Smahi.txt is : -
Ram
x=open("Smahi.txt", "rb") Shyam
x.seek(12) Ajay
print(x.tell()) Manoj
x.seek(-5,2) Rajeev
print(x.tell())
x.close()

Okay: - Cursor movement is


allowed from any where in
“BINARY FILE”
Let the content of the file
Smahi.txt is : -
Ram
em=open("Smahi.txt","rb") Shyam
z=em.read() Ajay
print(em.tell()) Manoj
em.seek(0,2) Rajeev
print(em.tell())
em.close() OUTPUT
33
33
0 moves from beginning

1 moves from current


position

2 moves from end


Shyam
em.seek(0,2)
Ajay
print(em.tell()) Manoj
em.seek(4,2)
Rajeev
print(em.tell())
em.seek(-4,2)
print(em.tell())
OUTPUT
em.close() 33
37
29
Shyam
em.seek(0,1)
Ajay
print(em.tell()) Manoj
em.seek(14,1)
Rajeev
print(em.tell())
OUTPUT
em.seek(-4,1) 0
print(em.tell()) 14
em.seek(3,1) 10
print(em.tell()) 13
em.close()
Shyam
em.seek(0,0)
Ajay
print(em.tell()) Manoj
em.seek(14,0)
Rajeev
print(em.tell())
em.seek(-4,0)
print(em.tell())
OUTPUT
em.close() 0
14
Error
“Start” Ram
em=open(“Smahi.txt","rb+")
Shyam
em.seek(100,0) Ajay
print(em.tell()) Manoj
em.close() Rajeev

OUTPUT
100
Here size of the file is 33 bytes,
but if we want to move beyond
the limit, its allowed but the size
of the file does not changes.
is : -
Ram
em=open(“Smahi.txt","rb+") Shyam
x=em.read() Ajay
print(em.tell()) Manoj
em.seek(100,0) Rajeev
print(em.tell())
OUTPUT
em.seek(0,0) 33
print(em.tell()) 100
y=em.read() 0
print(len(x)) 33
print(len(y)) 33
em.close() BUT……….
pointer beyond the
limit and tried to
write anything,
REMEMBER the
same will be written
at that point and the
size of the file will
expand.
em.seek(0,2)
OUTPUT
print(em.tell()) 33
em.seek(100,0)
print(em.tell())
100
em.seek(0,2)
print(em.tell()) 33
em.close()
OUTPUT
print(em.tell()) 33
em.seek(100,0)
print(em.tell())
100
em.write(b"Ramu")
em.seek(0,2)
print(em.tell())
104
em.close()
import pickle
emp1={'name':"amit", "age":23}
emp2={'name':"sumit",
"age":38}
emp3={'name':"ajay", "age":18}
em=open("emp.dat","wb")
pickle.dump(emp1,em)
pickle.dump(emp2,em)
pickle.dump(emp3,em)
print("Data dumped-written in
file.... ")
em.close()
em=open("emp.dat","rb")
print(em.tell())
try:
while True:
OUTPUT
emp=pickle.load(em) 0
print(em.tell())
42
except EOFError:
85
em.close()
127
Seek and Tell on Binary files
import pickle
emp={}
bmp=[]
em=open("emp.dat",'rb')
try:
while True:
emp=pickle.load(em)
bmp.append(em.tell())
except EOFError:
em.close()
print(bmp) [42, 85,
127]
Seek and Tell on Binary files

import pickle z=0


emp={} em=open("emp.dat",'rb')
bmp=[] emp=pickle.load(em)
em=open("emp.dat",'rb') print(emp)
try: while z<len(bmp)-1:
while True:
em.seek(bmp[z])
emp=pickle.load(em)
emp=pickle.load(em)
bmp.append(em.tell()) print(emp)
except EOFError: z=z+1
em.close() em.close()
Modifying the contents of a binary file
import pickle
x=input("Please enter name to be modified
")
y=open("emp.dat","rb+")
a={ }
try:
while True:
z=y.tell()
a=pickle.load(y)
if a['name']==x:
print(a['name'],' ',a['age'])
a['age']+=5
y.seek(z)
pickle.dump(a,y)
except EOFError:
y.close()
Modifying the contents of a binary file
(page 1)
import pickle
y=open("emp.dat","rb+")
a={}
try:
while True:
a=pickle.load(y)
print(a['name'],' ',a['age'])
except EOFError:
y.close()
continued ………… go to next
slide
Modifying the contents of a binary file (Page 2)
x=input("\n\nPlease enter name to be modified ")
y=open("emp.dat","rb+")
a={ }
k=0
try:
while True:
z=y.tell()
a=pickle.load(y)
if a['name']==x:
print("Name found ")
a['age']=int(input("Enter new age "))
y.seek(z)
pickle.dump(a,y)
k=1
except EOFError:
y.close()
if k==0:
print("Sorry ",x," not found ") continued ……… go to
next slide
Modifying the contents of a binary file (Page
3)

y=open("emp.dat","rb+")
a={}
try:
while True:
a=pickle.load(y)
print(a['name'],' ',a['age'])
except EOFError:
y.close()
em=open("emp.dat","ab")
x=1
while x==1:
emp['name']=input("Please enter
name ")
emp['age']=int(input("Please enter
age "))
pickle.dump(emp,em)
x=int(input("Please enter 1 to
continue "))

print("Data dumped-written in file....


")
em.close()
Deleting records from a binary file
(Slide 1)
import os
import pickle
y=open("emp.dat","rb+")
a={}
try:
while True:
a=pickle.load(y)
print(a['name'],' ',a['age'])
except EOFError:
y.close()
Continued………... Goto Next
Slide
Deleting records from a binary file (Slide 2)
x=input("\n\nEnter name to be deleted ")
y=open("emp.dat","rb+")
z=open("bmp.dat","wb+")
a={}
b=0
try:
while True:
a=pickle.load(y)
if a['name']!=x:
pickle.dump(a,z)
else:
b=1
except EOFError:
y.close()
z.close()
if b==1:
print("Data found, and deleted ")
else:
print("Deletion not possible ")
os.remove("emp.dat")
os.rename("bmp.dat","emp.dat")
Continued………... Goto Next Slide
Deleting records from a binary file
(Slide 3)
y=open("emp.dat","rb+")
a={}
try:
while True:
a=pickle.load(y)
print(a['name'],'
',a['age'])
except EOFError:
y.close()
import pickle
emp={}
em=open("stud.dat","wb")
x=1
for xx in range(25):
print("\n")
emp['name']=input("Please enter name
")
emp['roll']=int(input("Please enter roll
"))
emp['marks']=int(input("Please enter
marks "))
pickle.dump(emp,em)
print("Data dumped-written in file.... ")
em.close()
def display():
import pickle
emp={}
em=open("stud.dat","rb+")
for xx in range(25):
print("\n")
print("Name roll marks")
try:
while True:
emp=pickle.load(em)

print(emp['name'],emp['roll'],emp['marks']
)
except EOFError:
em.close()
def modify():
import pickle
for xx in range(25):
print("\n")
x=input("Please enter name to be modified ")
y=open("stud.dat","rb+")
a={}
try:
while True:
z=y.tell()
a=pickle.load(y)
if a['name']==x:
print("Data found ")
print(a['name'],' ',a['marks'], ' ',a['roll'])
print(".......and modified ")
a['marks']+=5
y.seek(z)
pickle.dump(a,y)
except EOFError:
y.close()
import pickle
emp={}
em=open("stud.dat","ab")
x=1
for xx in range(25):
print("\n")
emp['name']=input("Please enter name
")
emp['roll']=int(input("Please enter roll
"))
emp['marks']=int(input("Please enter
marks "))
pickle.dump(emp,em)
print("Data dumped-written in file.... ")
em.close()
ch='y'
while ch=='y':
x=int(input("Enter \n1..overwrite\n2..append\
n3..display\n4..modify marks\n5..exit from a file "))
if x==1:
enter()
if x==2:
adding()
if x==3:
display()
if x==4:
modify()
if x==5:
break

ch=input("Press y to continue ")

You might also like