File Handling Full Notes
File Handling Full Notes
Advantages
✔ Data is stored permanently.
✔ Already existing data can be used.
✔ Large amount of data can be processed easily.
✔ Data can be stored in different files and methods.
Text file
Reading from text file
Sample file “today.txt”
Hello world!
We are learning File handling.
read()
Reads data from text file in read mode.
Stores data in string form.
Example
p=open(“today.txt”, “r”)
k=p.read()
print(k)
p.close()
Output:-
Hello world!
We are learning File handling.
Note- We can give integer value for specific character
reading.
p=open(“today.txt”, “r”)
k=p.read(5)
print(k)
p.close()
Output:-
Hello
readline()
It reads line by line (one line at a time)
p=open(“today.txt”, “r”)
k=p.readline()
print(k) → Hello world!
p.close()
readlines()
It reads data in string form (each line) and enclosed
with a list.
p=open(“today.txt”, “r”)
k=p.readlines()
print(k) →[“Hello world!”, “We are learning File handling.”]
p.close()
Questions on Text filename
Sample file - “today.txt”
Hello world!
We are learning File handling.
1. Reading all data from file.
2. Reading first 10 characters from file.
3. Reading all data using for loop.
4. Reading all data using while loop.
5. Counting total number of characters/Bytes in file.
6. Counting total number of vowels.
7. Counting total number of words.
8. Counting total number of lines.
9. Counting total number of 5 letter word.
10. Counting total number of lines starting from a
specific letter.
Example
p=open("today.txt","w")
p.write("Hello world!\n")
k="This is line\n"
p.write(k)
a=["Rahul\n","Diya\n","Suraj"]
p.writelines(a)
p.close()
Binary Files
What is pickling
Pickling is the process in which data is converted to
byte stream so that it can be stored in binary file.
Pickle module – Module used for binary file.
We will used two function of pickle module.
load() - It is used to read or load data from binary file.
Syntax – pickle.load(file_object)
dump() - It is used to store or dump data into binary
file.
Syntax – pickle.dump(data, file_object)
Example:-
import pickle
p=open("today.dat","wb")
pickle.dump("Hello world",p)
k=["Binary file",4,[5,6]]
pickle.dump(k,p)
p.close()
with open("today.dat","rb") as p:
k=pickle.load(p)
print(k)
k=pickle.load(p)
print(k)
Output
Hello world
['Binary file', 4, [5, 6]]
def read_binary():
p=open("today.dat","rb")
while True:
try:
k=pickle.load(p)
print(k)
except:
p.close()
print("End of file")
break
def search_binary(): #Searching data
p=open("today.dat","rb")
s=input("Enter searching Rollno")
find=False
while True:
try:
k=pickle.load(p)
if k[0]==s:
print(k)
find=True
p.close()
break
except:
p.close()
print("End of file")
break
if find==False:
print("Data not find")
def update_binary():# Updating data
p=open("today.dat","rb+")
r=input("Enter Rollno")
while True:
try:
location=p.tell()
k=pickle.load(p)
if k[0]==r:
p.seek(location,0)
r=input("Enter Rollno")
n=input("Enter name")
m=input("Enter Marks")
d=[r,n,m]
pickle.dump(d,p)
print("Data Updated")
break
except:
p.close()
break
def copy_binary():
n=input("Enter the file name - ")
p=open("today.dat","rb")
k=open(n+".dat","wb")
while True:
try:
data=pickle.load(p)
pickle.dump(data,k)
except:
print("Records Copied")
p.close()
k.close()
break
def delete_binary():
import os
p=open("today.dat","rb")
k=open("hello.dat","wb")
r=input("Rollno to delete")
while True:
try:
data=pickle.load(p)
if data[0]!=r:
pickle.dump(data,k)
except:
print("Deletion done")
p.close()
k.close()
break
os.remove("today.dat")
os.rename("hello.dat","today.dat")
k=None
while k!=0:
print("0 - Exit")
print("1 - Write")
print("2 - Append")
print("3 - Read")
print("4 - Search")
print("5 - Update")
print("6 - Copy")
print("7 - Delete")
c=int(input("Enter your choice"))
if c==0:
break
elif c==1:
write_binary()
elif c==2:
append_binary()
elif c==3:
read_binary()
elif c==4:
search_binary()
elif c==5:
update_binary()
elif c==6:
copy_binary()
elif c==7:
delete_binary()
Complete Program
import csv
def write_csv():
p=open("today.csv","w",newline='') #Newline
will always be Empty
w=csv.writer(p,delimiter="-") #Delimiter
is now - not ,
d=["Rollno","Name","Marks"]
w.writerow(d)
k='y'
while k=='y':
r=input("Enter Rollno")
n=input("Enter name")
m=input("Enter Marks")
d=[r,n,m]
w.writerow(d)
k=input("Another record (y/n)")
p.close()
def read_csv():
p=open("today.csv","r")
d=csv.reader(p)
for x in d:
print(x)
p.close()
def search_csv():
p=open("today.csv","r")
r=csv.reader(p)
roll=input("Enter the Rollno - ")
next(r)
for x in r:
if x[0]==roll:
print(x)
break
else:
print("Not Found")
c=True
while c!=0:
print("0 - Exit")
print("1 - Write")
print("2 - Read")
print("3 - Search")
c=int(input("Enter your choice - "))
if c==0:
break
elif c==1:
write_csv()
elif c==2:
read_csv()
elif c==3:
search_csv()
else:
print("Invalid choice")
continue