All Courses

How to Handle Files with Python OS Module?

Neha Kumawat

2 years ago

How to Handle Files with Python OS Module?

Different Kinds of Files | insideAIML
Table of Contents
  • Introduction
  • How to open a new file and write into it?
  • How to read contents of a file?


          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, function also needs to specify file access mode.
Below table gives the lists of various modes of os module of python.
Various modes of os module of python | insideAIML

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 function returns a file descriptor."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.
We should not forget to close the file after using it. It is done by using the close() function.

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 function. Below is an example use the following statements:"test_data.dat", os.O_RDONLY)

a =,20)

print (a.decode('utf-8'))
Note that, the 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.
File operation functions in the os module | insideAIML
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.
Keep Learning. Keep Growing. 

Submit Review