0% found this document useful (0 votes)
24 views

Data File Handling - Working With Binary Files

Uploaded by

FF gaming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
24 views

Data File Handling - Working With Binary Files

Uploaded by

FF gaming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 10
Visit to webs snpythonacbse com Chapter-7: File Handling File Handling -> Binary File 1 | Binary Files 2 _ | Python: pickle module 3 Writing Instance onto a file —Using pickle.dump() ‘a | Reading Instance from a binary file Using pickle.load() 5 Operations performed using Binary files: Page tof 10 Unit I: Computational Thinking and Programming -2 fe] > % 3 ct ) ‘Visit to website: learnpythondcbse.com DICER CAD betes * In this type of file, there is no terminator for a line and the data is stored after converting it into machine understandable binary language. * Operations on binary files are faster as no translation required. «Image files such as .jpg, .png, gif, etc., and documents such as .doc, .xls, .pdf, etc., all of them constitute binary files. Cee rey te Peer cay ab ead onl This is the default mode. It Opens file for reading. ¥ File must exists, otherwise Python raises |/O errors This Mode Opens file for writing. ‘wb’ Write only Iffile does not exist, it creates a new file. If file exists it truncates the file. File is in write mode only, new data will be added ‘ab’ Append to the end of existing data i.e. no overwriting. If file not exists it creates a new file “r+b’ or ‘rb+” Read and write File must exists otherwise error is raised Both reading and writing can take place “web! or ‘whe! Write and read File is created if not exists, if exists data will be truncated, both read and write allowed ‘atb! or ‘abt’ Write and read Write Same as above but previous content will be retained and both read and write. Opens a file for exclusive creation. If the file already exists, the operation fails. Write and read Similar to w+ as it will create a new file if the file does not exist. Otherwise, will raise FileExistsError. Page 2 of 10 Unit I: Computational Thinking and Programming -2 Visit to website: learnpythondcbse.com Chapter DICER CAD betes * Sometimes we need to write and read structure objects such as dictionary, list and the objects/instance of a class ona file * Python has a module which does this work for us and is extremely easy to use. This module is called pickle. © It provides us with the ability to serialize (by using dump () method) and deserialize (by using load () method) objects, i.e., to convert objects into bitstreams which can be stored into files and later be used to reconstruct the original objects. © There are some data types which pickle cannot serialize, but it is still capable of serializing most of the objects typically used in Python programs. A comprehensive list of data types which pickle can serialize. — None, True, and False — integers, floating point numbers, complex numbers — strings, bytes, bytearrays — tuples, lists, sets, and dictionaries containing only picklable objects — functions defined at the top level of a module (using def, not lambda) — built-in functions defined at the top level of a module — classes that are defined at the top level of a module In order to work with pickle module, you must import pickle in your program. Page 3 of 10 Unit I: Computational Thinking and Programming -2 Visit to website: learnpythondcbse.com Chapter-7: File Handli Writing Instance onto a file -Using pickledumpQ = © pickle.dump() function to store the object data to the file. * pickle.dump () method is used to write object in the file or to serialize an object hierarchy. Syntax of dump (): pickle.dump(object_to_be written, fileObject) Example: Program to write structure, dictionary to the binary file. (a binanpy-CUsersdiniAppDstlloc Program Phe Phon6-abinanpy 365.0 (=| Fie Ean Format fun Options Window Hob import pickle F # Program to write structure, dictionary to binary file {J # An arbitrary collection of objects supported by pickle. data U1, 2.0, 3, 446j], ("character string", b"byte string"), {None, True, False} with open("bin data.dat', ‘wb') as fr # Pickle the 'data' dictionary. pickle.dump(data, £) Fie_Edt_Forat_Ver Hep e nck GB The contents of the generated ary Eee teins cipal ft file are encrypted (serialized) in binary: |{airqiex baxt character strigecrbyteretringta x icqcbu1 Itinssetq?]q#( Ne..gRqfu. * To retrieve pickled data, you have to use pickle.load|) function to do that. * pickle. 1oad( ) method unpickle or unserialize the data coming from the file Page 4 of 10 Unit Computational Tiling and Progamming 2 Vi to webs lenanthonbee com Chapter-7: File Handli Syntax of load() : Object = load (£ileobject) The primary argument of pickle load function is the file object that you get by opening the file in read-binary (rb) mode. Example: Te read dictionary from the binary file “ bin_data.dat” ([[File fait Format Run Options Window Help # Example: dictionary from the binary file * with open('bin_data.dat', 'rb') as ft # Unpickle the 'data' dictionary. Mydata = pickle.load(f) print (Mydata) OUTPUT: [prose ae tat at Opens den hap \users\Adnin\AppData\Local \Programs\rython\Python36-32\binary. py a 3, (4*6))1, "bY: (Tcharacter string", brbyte string’), ‘et? (false, True, wone)) a) Reading from Binary file b) Writing to Binary File ¢) Appending record ( inserting record at the end of the file) d) Searching Record in Binary file e) Deleting record from Binary file f) Copying a file g) Modification/ Updation in Binary File. Page Sof 10 ‘Visit to website: learnpythondcbse.com Unit I: Computational Thinking and Programming -2 Chapter-7: File Handling 2 author: learnpythonacbse.com ze 4 import pickle 5 : cratic ‘ Ge ay file 741 r/Appendi 8 1 943 ; 1044. 1 2 F def Writerecord(sroll, snane, sperc, remark) : 14 with open ("StudentRecord.dat","ab") as Myfile 15 srecord={"SROLL":sroll, "SNANE":sname, "SPERC™: 16 "SREMARKS" : sremark) 17 pickle.dump(srecord,Myfile) 18 19def Readrecord(): 20 with open (*StudentRecord.dat',"rb") as Myfile: 2 print (*\n------DISPALY STUDENTS DETAILS. 2 print("\nRoll No.”," ", "Name" ,"\t' ,end= 2B print(‘Percetage’," *,"Remarks") 24 while True: 25 try: 26 rec=pickle. load(Myfile) 2” print(* ",rec["SROLL"],"\t * yrec{"SNAME'], "\t "end: 28 print(rec["SPERC'],"\t —",rec["SREMARKS']) 29 except EOFError: 30 break Di def Input(): 32 neint(input("How many records you want to create :")) 33 for ete in range(a): 3 sroll=int(input("Enter Roll Wo")) 35 sname=input("Enter Name: ") 36 sperc=float(input("Enter Percentage: ")) 37 sremark=input("Enter Remark: ") 38 Writerecord(sroll, sname,sperc, sremark) 39 40 def SearchRecord(rol1): 41 with open (‘StudentRecord.dat","rb") as Myfile: a2 while Tru 3 try: 44 rec=pickle. load(Myfile) 45 if rec 'SROLL" J==rol1: 46 print("Roll NO:",rec{ "SROLL" }) a7 print("Name:” rect "SNAME"]) 48 print(“Percentage:” reef “SPERC*}) 49 print("Remarks:" ,rec[ "SREMARKS']) 50 except £OFError: 51 break ge 6 of 10 Unit I: Computational Thinking and Programming -2 Visit to website: learnpythondcbse.com Chapter-7: File Handling 52 - Si def Modify(roll,name,perc,remark): 54 with open (‘StudentRecord.dat','rb") as Myfile: 55 56 57 try: 58 rec-pickle. load(Myfile) 59 newRecord.append(rec) 60 except EOFError: 61 break 62 for i in range(len(newRecord)): 68 if newRecord[i]["SROLL 64 newRecord{i] [ “SNAKE 65 newRecord{i]['SPERC’]=perc 66 newRecord[i]["SREMARKS’ ]=remark 67 with open (‘StudentRecord.dat',‘wb') as Myfile: 68 for jin newRecord: 69 Pickle.dump(j,MyFile) 70 7. def DeleteRecord(roll): 72 with open (“StudentRecord.dat',‘rb") as Myfile: B newRecord 7 while True: 5 try: 76 rec=pickle. load (Myfile) 7 newRecord. append(rec) 7 except EOFError: 73 break 80 with open (*StudentRecord.dat',"wb") as Myfile: al for i in newRecord: 2 if A['SROLL' Jesroll: 3 continue 84 pickle.dump(i,Myfile) 85 p 6 def main(): 87 88 while True: 89 print("\nYour Choices are: *) 90 print('1.Insert Records’) 1 print(‘2.0ispaly Records’) 92 print("3.Search Records (By Roll No)" 3 print('4.Update Records") 94 print('s.Delete Records’) 95 print('0.Exit (Enter @ to exit)") 96 int(input(‘Enter Your Choice: *)) 97 Af cheel: 98 99 100 101 elif d 402 reint(input("Enter a Rollno to be Search")) 103 SearchRecord(r) ge 7 of 10 104 105 106 107 108 109 10 111 112 113 a 115 main() 116 Unit I: Computational Thinking and Programming -2 OUTPUT: on next page ‘Visit to website: learnpythondcbse.com Chapter-7: File Handling fF int(input(“enter a Rollno to be update: *)) nane=input("Enter Name to be update: ") perc=float(input("Enter Percentage to be update: “)) remark-input("Enter renarks to be update: “) Modify(r,name,perc,renark) elif ch==5: rr =int(input("Enter a Rollno to be delete: DeleteRecord(r) else: break ge 8of 10 Unit I: Computational Thinking and Programming -2 Chapter-7: File Handling ‘Visit to website: learnpythondcbse.com cal cone a mal |G) ono In [2]: runfile("D:/Amjad_Cs/BinFileop.py', “| |!Your choices are: lwdir="D: /Amjad_Cs*) Lunsert Records Your Choices are: ‘LInsert Records 2.Dispaly Records 3,Search Records (By Roll No) 4.Update Records 5.Delete Records O.Exit (Enter 0 to exit) Enter Your Choice: 1 How many records you want to create Enter Roll No 1 Enter Name: anit Enter Percentage: 29 Enter Remark: Good Enter Roll No: 2 Enter Nane: Anaan Enter Percentage: 90 Enter Remark: V Good Your Choices aré ‘Insert Records 2.Dispaly Records 3:Search Records (By Roll No) 4.Update Records 5.Delete Records O.Exit (Enter 0 to exit) Enter Your Choice: 2 -DISPALY STUDENTS DETAILS- Roll No. Name Percetage Remarks 1 amit 99.0 Good 2 aman 90.0 V Good fivicns: RW “ings CRLF ng: ASCE Lin 24 Col 50 Mem 769% 2.Dispaly Records search Records (By R011 No) 4-Update Records S.Delete Records OlExit (Enter @ to exit) Enter Your choice: 3 [Enter a Rollno to be Search: 2 Roll NO: 2 Name: Anan Percentage: 90.0 Remarks: V Good Your Choices a LiInsert Records 2.Dispaly Records '3:Search Records (By Roll No) 4.update Records S.belete Records O.Exit (Enter @ to exit) Enter Your Choice: 4 Enter a Rollno to be update: 2 Enter Name to be update: Anaan Ali Enter Percentage to be update: 90 Enter remarks to be update: V Good Your Choices are: Insert Records 2.0ispaly Records 3.Search Records (By Roll No) update Records S.Delete Records lo-Exit (Enter @ to exit) Enter Your choice: 2 ------DISPALY STUDENTS DETAILS - Roll No. Name 1 anit 2 Amaan Ali Percetage Remarks V Good Page 9 of 10 Unit I: Computational Thinking and Programming -2 ‘Visit to website: learnpythondcbse.com Chapter DICER CAD betes Roll No. 2 In [2]: DISPALY STUDENTS DETAILS- Your Choices are: 1.Insert Records 2.Dispaly Records 3.Search Records (By Roll No) 4.Update Records 5.Delete Records 0.Exit (Enter 0 to exit) Enter Your Choice: 5 Enter a Rollno to be delete: 1 Your Choices are: 1.Insert Records 2.Dispaly Records 3.Search Records (By Roll No) 4.Update Records 5.Delete Records 0.Exit (Enter @ to exit) Enter Your Choice: 2 Name Percetage Remarks Amaan Ali 90.0 V Good Your Choices are: 1.Insert Records 2.Dispaly Records 3.Search Records (By Roll No) 4.Update Records 5.Delete Records 0.Exit (Enter @ to exit) Enter Your Choice: 0 lines: RLF ding: ASCE __Lin 21 Col SO Mem 779% Page 10 of 10,

You might also like