Python Data Persistence – File Handling using os Module

Python Data Persistence – File Handling using os Module

Python’s built-in library has an os module that provides useful operating system-dependent functions. It also provides functions for performing low-level read/write operations on the file. Let us briefly get acquainted with them.

The open () function from the os module (obviously it needs to be referred to as os. open ( )) is similar to the built-in open ( ) function in the sense it also opens a file for reading/write operations. However, it doesn’t return a file or file-like object but a file descriptor, an integer corresponding to the file opened. File descriptor’s values 0, 1, and 2 are reserved for stdin, stout, and stder r streams. Other files will be given an incremental file descriptor. Also, the write ( ) and read( ) functions of the os module needs bytes to object as the argument. The os .open () function needs to be provided one or combinations of the following constants: (Table 5.2)

os.OWRONLY open for writing only
os.ORDWR open for reading and writing
os.OAPPEND append on each write
os.OCREAT create file if it does not exist
os.OTRUNC truncate size to 0
os.OEXCL error if create and file exists

As in the case of a file object, the os module defines a sleek () function to set file r/w position at the desired place from the beginning, current position, or end indicated by integers 0,1, and 2 respectively.


>>> fd=os . open ("testfile. txt", os .0_RDWR | os .0_CREAT)
>>> text="Hello Python"
>>> encoded=text.encode(encoding='utf-16')
>>> os.write(fd, encoded)
>>> os.lseek(fd,0,0)
>>> os.path.getsizeCtestfile.txt") #calculate file size
>>>, 26)
>>> text=encoded.decode('utf-16 ')
>>> text
'Hello Python'