Data File Handling
To store the data in secondary storage device through Python program, Data File Handling mechanism is used. To handle several types of data, different types of files are used.Video: (5:45 min) Need of Data File Handling and reading a simple text file using Python
Types of files:
1. Text File2. Binary File
3. CSV file
Text file: A text file can be understood as a sequence of characters consisting of alphabets, numbers and other special symbols. Files with extensions like .txt, .py, .csv, etc. are some examples of text files.
Binary file: Binary file represent the actual content such as image, audio, video, compressed versions of other files, executable files, etc. These files are not human readable. Binary files are stored in a computer in a sequence of bytes.
CSV (Comma Separated Value) file: These files are text file only except its extension is .csv. They can be opened in spreadsheet format.
File open Mode:
File mode Description
'r' Open text file for reading. Raises an I/O error if the file does not exist.
'w' Open the file for writing. Truncates the file if it already exists. Creates a new file if it does not exist.
'a' Open the file for writing. The data being written will be inserted at the end of the file. Creates a new file if it does not exist.
'r+' or '+r' Open the file for reading and writing. Raises an I/O error if the file does not exist.
'a+' or '+a' Open the file for reading and writing. The data being written will be inserted at the end of the file. Creates a new file if it does not exist.
'rb' Open the file for reading in binary format. Raises an I/O error if the file does not exist.
'a' Open the file for writing. The data being written will be inserted at the end of the file. Creates a new file if it does not exist.
'r+' or '+r' Open the file for reading and writing. Raises an I/O error if the file does not exist.
'a+' or '+a' Open the file for reading and writing. The data being written will be inserted at the end of the file. Creates a new file if it does not exist.
'rb' Open the file for reading in binary format. Raises an I/O error if the file does not exist.
'ab' Open the file for appending in binary format. Inserts data at the end of the file. Creates a new file if it does not exist.
'wb+' or '+wb' Open the file for reading and writing in binary format. Truncates the file if it already exists. Creates a new file if it does not exist.
f=open('a.txt','r')
x=f.read(10)
print(x)
input()
x=f.read(5)
print(x)
input()
x=f.read(5)
print(x)
input()
x=f.read()
print(x)
input()
f.close()
'wb+' or '+wb' Open the file for reading and writing in binary format. Truncates the file if it already exists. Creates a new file if it does not exist.
Video: (7:46 min) File Modes and Types of File
read(): Function: This function reads the byte(s) of stream or entire text from current position of file pointer from text file and returns it in the form of string.
#Program to demonstrate read functionf=open('a.txt','r')
x=f.read(10)
print(x)
input()
x=f.read(5)
print(x)
input()
x=f.read(5)
print(x)
input()
x=f.read()
print(x)
input()
f.close()
readline(): Function: This function reads a single line from current position of file pointer from text file and returns it in the form of string. The function stops reading as soon as it encounters '\n' (newline) character.
#Program to demonstrate readline functionf=open('a.txt','r')
x=f.readline()
print(x)
input()
x=f.readline(5)
print(x)
input()
x=f.readline(2)
print(x)
input()
x=f.readline()
print(x)
input()
# ...... More number of readline functions can be used depending upon the content of text.
f.close()
readlines() function: This function reads all the lines of text file and stores them in the form of list.
#Program to demonstrate readlines function
f=open('a.txt','r')
x=f.readlines()
print(x)
input()
x=f.readlines()
print(x)
input()
f.close()
write() and writelines() functions: This function writes the text from python program to text file.
f=open("abc.txt","a")
f.write("1111\n")
f.writelines['123\n','xyz\n','4563\n'])
f.close()
Reading and writing Binary files:
# Writing in binary file
import pickle
f=open('a.dat','wb')
L=[34,56,3,12,87,7]
pickle.dump(L,f)
f.close()
# Reading from binary file
import pickle
f=open('a.dat','rb')
x=pickle.load(f)
print(x)
f.close()
# Adding records in binary file
#Adding records in Binary File
import pickle
f=open("data1.dat","ab")
#Accepting data from user
c='y'
while c=='y':
n=int(input("Enter Roll Number:"))
name=input("Enter Name:")
marks=float(input("Enter marks:"))
#Writing data to binary file
data=[n,name,marks]
pickle.dump(data,f)
print("Record added successfully !")
c=input("Do you want to enter more records? (y/n)")
if c not in ['y','Y']:
break
f.close()
#Display data
f=open("data1.dat","rb")
try:
while True:
d=pickle.load(f)
print(d)
except:
print("*** End of records ***")
f.close()
Video (4:03 min): Adding records in Binary file
Searching in binary file:
#Searching records in Binary File
import pickle
f=open("data1.dat","rb")
#Display data
print("Present data in file:")
try:
while True:
d=pickle.load(f)
print(d)
except:
print("*** End of records ***")
# Search record
n=int(input("Enter Roll Number to be searched: "))
f.seek(0)
try:
while True:
r=pickle.load(f)
if r[0]==n:
print(r)
break
else:
pass
except:
print ("No record found ...")
finally:
f.close()
Updating Records in Python's Binary file
#Updating records in Binary File
import pickle
import os
f=open("abc.dat","rb")
#Display data
print("Present data in file:")
try:
while True:
d=pickle.load(f)
print(d)
except:
print("*** End of records ***\n")
# Update record
n=int(input("Enter Roll Number to be updated: "))
m=float(input("Enter new marks "))
f1=open("temp.dat","ab")
f.seek(0)
try:
while True:
r=pickle.load(f)
if n != r[0]:
pickle.dump(r,f1)
else:
r1=[n,r[1],m]
pickle.dump(r1,f1)
except:
print ("** End of records **")
finally:
f.close()
f1.close()
os.remove("abc.dat")
os.rename("temp.dat","abc.dat")
#Display data
print("\nUpdated data in file:")
f=open("abc.dat",'rb')
f.seek(0)
try:
while True:
d=pickle.load(f)
print(d)
except:
print("*** End of records ***\n")
f.close()
Delete records in Binary file
#Deleting records in Binary File
import pickle
import os
f=open("abc.dat","rb")
#Display data
print("Present data in file:")
try:
while True:
d=pickle.load(f)
print(d)
except:
print("*** End of records ***\n")
# Delete record
n=int(input("Enter Roll Number to be Deleted: "))
f1=open("temp.dat","ab")
f.seek(0)
try:
while True:
r=pickle.load(f)
if n != r[0]:
pickle.dump(r,f1)
else:
pass
except:
print ("** End of records **")
finally:
f.close()
f1.close()
os.remove("abc.dat")
os.rename("temp.dat","abc.dat")
#Display data
print("\nUpdated data in file:")
f=open("abc.dat",'rb')
f.seek(0)
try:
while True:
d=pickle.load(f)
print(d)
except:
print("*** End of records ***\n")
f.close()
No comments:
Post a Comment