Python provides us a
module name OS module which provides different functions which helps us to
interact with our operating system. This module gives a portable way of using
operating system dependent functionality.
These functions perform low level
read/write operations on the file.
The open() function from the os
module is similar to the built-in open(). However, it doesn't return a file
object but a file descriptor which is a unique integer corresponding to the file
opened.
File descriptor's values 0, 1, and 2 represent
stdin, stdout, and stderr streams. Other files will be given incremental file
descriptors from 2 onwards.
As in case of open() built-in
function, os.open() function also needs to specify file access
mode.
Below table gives the lists of various modes of
os module of python.
How
to open a new file and write into it?
If you want to open a new file for writing data
into it we have to specify O_WRONLY as well as O_CREAT modes
by inserting the pipe (|) operator. The os.open() function returns a file
descriptor.
f=os.open("test.dat", os.O_WRONLY|os.O_CREAT)
Note: The data is written into a disk file in the form
of a byte string. Hence, a normal string is converted to byte string by using the encode() function as earlier.
a = ("Hello User".encode('utf-8'))
The write() function in the os module will accept
this byte string and file descriptor.
os.write(f,a)
We should not forget to close the file after
using it. It is done by using the close() function.
os.close(f)
How to read contents of a file?
Now
if you want to read the contents of a file it can be done by using the os.read() function. Below is an example use the following statements:
f=os.open("test_data.dat", os.O_RDONLY)
a = os.read(f,20)
print (a.decode('utf-8'))
Note that, the os.read() function needs file
descriptor and number of bytes to be read (length of byte string) from the
given file.
If you want to open a file for simultaneous
read/write operations, use O_RDWR mode.
Below table shows some of the important files
operation related functions in the os module which is most used.
Like the Blog, then Share it with your friends and colleagues to make this AI community stronger.
To learn more about nuances of Artificial Intelligence, Python Programming, Deep Learning, Data Science and Machine Learning, visit our insideAIML blog page.