Python Data Persistence – Simultaneous Read/Write

Python Data Persistence – Simultaneous Read/Write

Modes ‘w’ or ‘a’ allow a file to be written to, but not to be read from. Similarly, ‘r’ mode facilitates reading a file but prohibits writing data to it. To be able to perform both read/write operations on a file without closing it, add the ‘+’ sign to these mode characters. As a result ‘w+’, ‘r+’ or ‘a+’ mode will open the file for simultaneous read/write. Similarly, binary read/ write simultaneous operations are enabled on file if opened with ‘wb+’, ‘rb+’ or ‘ab+’ modes.

It is also possible to perform read or write operations at any byte position of the file. As you go on writing data in a file, the end of file (EOF) position keeps on moving away from its beginning. By default, new data is written at the current EOF position. When opened in ‘r’ mode, reading starts from the 0th byte i.e. from the beginning of the file.
The seek ( ) method of file object lets you set current reading or writing position to a desired byte position in the file. It locates the desired position by counting the offset distance from beginning (0), current position (1), or EOF (2). Following example illustrates this point:

Example

>>> file=open ("testfile . txt", "w+")
>>> file .write ("This is a rat race")
>>> file.seek(10,0) #seek 10th byte from beginning
>>> txt=file . read (3) #read next 3 bytes
>>> txt
' rat'
>>> file . seek (10,0) #seek 10th byte position
>>> file . write ('cat' ) #overwrite next 3 bytes
>>> file.seek(0)
>>> text=file . read () #read entire file
>>> text
'This is a cat race'
>>> file . close ( )

Of course, this may not work correctly if you try to insert new data as it may overwrite part of existing data. One solution could be to read the entire content in a memory variable, modify it, and rewrite it after truncating the existing file. Other built-in modules like file input and map allow modifying files in place. However, later in this book, we are going to discuss a more sophisticated tool for manipulating databases and update data on a random basis.