Saturday, March 23, 2019

Serial, Sequential and Random Access File Organization Using Python

Records in a file can be stored in different ways:

  • Serial - records are kept without defined /specific order.They are stored as they happened like how we store deposit/withdrawal transactions. We append them after each other.
  • Sequential - Unlike serial, sequential requires the use of key field (like an ID) and organize them using this ID. 
  • Random - Serial and sequential records may be searched from beginning until the record is found. This cant be possible if we need fast access (like ATM bank query or withdrawal). So, random file requires that we store and search a record in any address (usually defined by a hash function).
See the program code below in Python how records are stored and searched using serial organization in a text file:

Now, using random file organization, we can use binary file to implement random access where seek ( ) is used to locate an address and dump( )  is used to write into the binary file and load( ) to read from the binary file. Know that we can also use text files to implement random and sequential organization. We only use binary file as these are the common file formats used be executable files and other software.

Unlike text files where we use the file mode: w (write), r (read),a (append), binary files use the following file mode: wb (write binary), rb (read binary), rb+ (read and append), you may use other file modes  too.

Writing to binary file:

Reading from binary file:

Please note that unlike text files, binary file keep records in its internal representation, meaning, you may special characters in the file as you open it in a text editor like Notepad.

Now try these and explore.