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.
Types of files:
1. Text File
2. 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' Opens a file in read mode
'w' Opens a file in write mode
'a' Opens a file in append mode
'r+' or '+r' Opens a file in both read and write mode
'a+' or '+a' Opens a file in both read and append mode
'rb' Opens a file in binary and read-only mode
'wb+' or '+wb' Opens the file in read,write and binary mode.
Open function:
Syntax: file_object= open(file_name, access_mode)
Example: f1 = open('abc.txt','w')
Activity 1:
Execute open and write method using PC.
Activity 2:
Write any string in text file inputted by the user.
Writing to a text file
1. Open the file
2. Execute write command
3. Close the file
write() method:
file_handle.write(<string to write>)
Example: f.write("Hello")
writelines() method:
Example: f.writelines("abc","def","mnp","pqr")
Activity 3:
Execute writelines() method by taking few names from user one by one and write them in a text file in separate lines.
Reading from text file:
read([n])
readline([n])
readlines()
Activity 4: Reading any content from a text file and display it on screen.
Activity 5: Reading the 5th character onwards in 3rd line in a text file.
Activity 6: Counting total number of characters in a text file.
Activity 7: Counting all the 'a' and 's' in a text file.
Activity 8: Counting all the lines starting with 'a'
seek() function
tell() function
Activity 9: Execute the functions seek() and tell() in Python
Activity 10: Counting number of words in a text file.
Binary files:
dump()
load()
Writing binary data:
import picklerecord = []
while True:
rn=int(input("Roll No? "))
name=input("Name? ")
marks=float(input("Marks? "))
data=[rn,name,marks]
record.append(data)
choice=input("More records? (Y/N) ")
if choice.lower()=='n':
break
f=open("student.dat","wb")
pickle.dump(record,f)
print("Record Added")
f.close()
Reading and searching record from binary file:
import picklef=open("student.dat","rb")
n=int(input("Enter the Roll Number to be searched "))
st_rec=pickle.load(f)
print(type(st_rec))
for i in st_rec:
if i[0]==n:
print(i)
f.close()
No comments:
Post a Comment