Python OS Module – Opening and reading files

Welcome back, everyone. In this lecture, we’re going to be focusing on built-in modules that relate to Python OS Module – opening and reading files and folders on your computer.

Pythons OS module allows us to easily navigate files and directories on the computer and then perform actions on them, such as moving them or deleting them.

Let’s go ahead and explore these Python OS module and get started.

First we have to know how to read file manually one by one in python.

Let’ we have a file named demo.txt in the current directory. If you don’t, just create one, and then fill with few lines and save it. I hope you are ready to open the saved file.

myfile = open("demo.txt")
txt =

Or, You can also do with this:

myfile = open("demo.txt")

So far we’ve discussed how to open files manually, one by one. Let’s explore how we can open files programmatically.

Getting Directories

Python has a built-in os module that allows us to use operating system dependent functionality.

You can get the current directory:

import os

Listing Files in a Directory

You can also use the os module to list directories.


If I run this command in my Jupiter notebook, Output will be:

 'Application Data',
 'Local Settings',
 'Saved Games',
 'tic tak toi.ipynb',

You can also pass the directory path in this command like:

python os module

Moving Files

You can use the built-in shutil module to move files to different locations. Always Keep in mind, there are permission restrictions, for example, if you are logged in a User A, you won’t be able to make changes to the top-level Users folder without the proper permissions, more info

import shutil
Output: 'C:\\Users\\diksh\\demo.txt'

Deleting Files

NOTE: The os module provides 3 methods for deleting files:

  • os.unlink(path) which deletes a file at the path you provide
  • os.rmdir(path) which deletes a folder (folder must be empty) at the path your provide
  • shutil.rmtree(path) this is the most dangerous, as it will remove all files and folders contained in the path. All of these methods can not be reversed! This means if you make a mistake you won’t be able to recover the file.

Different commands of Python OS Module

  • This function returns the name of the operating system dependent module imported. Let us have the few names that have currently been registered: ‘java’ and ‘riscos’. example:
import os 
Output: java
  • this function is used for reading files.
  • os.getcwd: it returns the (CWD) current Working Directory of the file used to execute the code, it can vary from system to system.
  • os.error: All functions in this module raise OSError in the case of invalid file names and paths, or other arguments that have the correct type. But they are not accepted by the operating system. The python os.error is an alias for built-in OSError exception.
import os 
    # If the file does not exist, 
then it would throw an IOError 
    filename = 'file.txt'
    a = open(filename, 'rU') 
    text = 
# Control jumps directly to here if any of the above lines throws IOError.     
except IOError: 
    # print(os.error) will <class 'OSError'> 
    print('Problem reading: ' + filename)
  • os.popen(): This method is used to open a pipe to or from command. The returned value can be read or written depending upon whether the mode is ‘r’(read) or ‘w’(write). Syntax:
 os.popen(command[, mode[, bufsize]])

The Parameters – mode & bufsize are not necessary parameters, if we does not provide value of both, the default ‘r’ is taken for the mode.

  • os.close(): Using this we can close the already opened file. A file opened using open() command, it can be closed by close() only. But in case of a file which is opened by os.popen(), that can be closed with close() or os.close(). If we try closing a file opened with open(), using os.close(), Python would throw the TypeError.
import os 
f = "file.txt"
file1 = open(f, 'r') 
text = 

Output will be:

python os module
  •  os.rename(): A file A.txt can be renamed to B.txt, using the function os.rename(). The name of the file changes only if, the file exists, and also the user has privilege permission to change the file name. Example: I don’t save the GFG.txt in my system, below mentioned code will throw an error.
import os 
f = "GFG.txt"


python os module

Related Topics:

All right. So that’s it for this topic, we have discussed the Python OS module with suitable examples. I hope these can really help you and I will see you at the next topic.

5 thoughts on “Python OS Module – Opening and reading files

Leave a Reply

Your email address will not be published. Required fields are marked *