Table of contents
1.
Introduction
2.
OS Error 
2.1.
Examples
2.2.
Error Handling
3.
Frequently Asked Questions
4.
Conclusion
Last Updated: Mar 27, 2024

The OSError in Python

Author Yashesvinee V
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The OS module in Python contains a collection of functions that help programmers interact with the Operation system. These methods aid in performing tasks involving files, directories and other OS-related jobs.  All functions of this module raise an OSError when invalid arguments or inaccessible file names and paths are passed to it.

You can also read about the Multilevel Inheritance in Python and Convert String to List Python.

OS Error 

OSError is a built-in exception that serves as an error class for the functions present in the os module. It is raised when the os specific system function returns a system-related or I/O error.

The OSError exception has two constructors. Thus, the programmer can receive a description of the OSError in two formats.

  • exception OSError([arg])
     
  • exception OSError(errno, strerror[, filename[, winerror[, filename2]]])
     

Arguments:

  1. errno is a numeric error code.
  2. strerror is the corresponding error message, as provided by the operating system.
  3. filename/filename2 arguments are set for errors that arise in functions involving file system paths.
  4. winerror exists only under Windows. It gives the native Windows error code.
     

The arguments are set to null unless specified. The constructor often returns a subclass of OSError, and this subclass depends on the final errno value.

 

Also see - Difference between argument and parameter

Examples

import os
# The close() method is used to close the given file descriptor.
# Since 50 is not a valid file descriptor, it throws an OSError
os.close(50)
You can also try this code with Online Python Compiler
Run Code

 

Output:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    os.close(50)
OSError: [Errno 9] Bad file descriptor

 

The following examples show the different ways of producing an OSError.

 

In the above example, OSError is thrown as the string provided does not truly represent the correct file path according to Python. All backslashes in the string can be escaped, or the path can be passed as a raw string to resolve this error.
 

PermissionError is a subclass of OSError (OSError : [Errno 30]). It is thrown when one attempts to write into a read-only file.
 

NotADirectoryError (OSError : [Errno 20]) and FileNotFoundError are also subclasses of OSError and are raised according to the system error code generated.

Recommended Topic, Divmod in Python, Fibonacci Series in Python

Error Handling

OSErrors can usually be prevented by ensuring the existence of the files and directories that are being accessed. OSError, like all other errors, can be handled using try-except blocks. Here’s an example.

import os
try:
    file1 = open("C:\\Users\Yashesvinee\Documents\myfolder\newfile.txt",'r')
    print(file1.read())
except:
    print("Something went wrong. Please enter the correct path.")
You can also try this code with Online Python Compiler
Run Code


Output:

Something went wrong. Please enter the correct path.

 

You can try it on online python compiler.

Check out Escape Sequence in Python

Frequently Asked Questions

  1. Which subclass of OSError is invoked when we try to create a file or directory that already exists?

    FileExistsError is invoked when we try to create a file or directory that already exists. Its system error code is OSError [Errno 17].
     
  2. What is OSError [Errno 22]?

    OSError [Errno 22] implies an Invalid Argument. This may occur when reading, writing or saving a file.

Conclusion

This article extensively discusses the OSError in Python. We hope that this blog has helped you enhance your knowledge about types of OS errors and how to handle them. If you would like to learn more, check out our articles try-except for Exception Handling and OS module.

Recommended Readings:

Explore our Coding Ninjas Library and upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass