Append Data to Binary File in Python Programming

Note: Binary files are always written in structure form and later it is converted to byte stream before storing to binary file. By structure from I mean to say in formats like lists, tuple, sets, dictionary etc.

Append data to Binary File: As we know that binary files written in structure form list, tuple etc. So, to append any new data to our binary file we need to use append() function same as we did in writing data to binary file in python. Just only difference is the file mode. We use “ab” for appending data to our Binary File.

append-data-to-binary-file


Problem Solving Approach:
 
Basically our requirement is that we will keep on asking to user to enter records till he was not done with entering records. We also need to keep in mind that we have to perform operation without deleting or over writing previous records that was already written in file.

Example: I have a file “bin.dat” storing some records of students.

file: “bin.dat
append-data-to-binary-file
Now we will write a program to append one more student data to our file “bin.dat”.

append-data-to-binary-file-1


Explanation: 
Here our program is same as that we did in writing multiple data to Binary File. But the only difference is that here we have used “ab” file mode. But in our previous program (writing multiple data to Binary File) we used “wb” file mode.

Available file modes

Step 1: Here we have opened our already existing file “bin.dat” in append mode for adding more records to our binary file.

Step 2: We created an empty list rec[] in which we append data and later we dump that data to our file.

Step A: Here is the our while loop() which is by default set to True, so that user can enter to while loop() to append data.

Step 3: At this step, we are only taking details of student as an input.

Step 4: Here we have created a new list data. In this list we are storing the inputs that we have taken from user.

Step 5: Here we are appending our list data[] which is storing the inputs given by user as details of student to our previous list rec[].

Step 6: Now the new record of student has been appended to our file. Here at step 6, we will ask user to enter his choice as Y/N . to continue to writing data or to stop writing more data.

Step 7: Here condition is checked that user entered Y/N as a choice. If choice entered is N then loop will stop executing. And exit the while loop.

Step 8: Here we are appending the data input taken from user to our binary file “bin.dat”.

Step 9: This is the function definition of reading all records from our binary file “bin.dat”.

Step 10: Here we are calling our read() function.

Hence we can append data to our Binary File.