Python OS Module : Errors














































Python OS Module : Errors




Python OS Module : Errors 



Errors and exceptions

 1.os.error 

os.error: It is environment error class for I/O errors. OSError is raised when any function returns any system-related error. Each of the os module functions returns these errors when any invalid or inaccessible file is triggered.

>>> import os
>>> try:
... fileName='osmodule.txt'
... f=open(fileName,'r')
... text=f.read()
... f.close()
... except os.error:
... print("error in "+fileName)
...
error
in osmodule.txt
>>> f=open(fileName,'r')


Output:



>>> try:
... fileName='/home/soumi/osmodule.txt'
... f=open(fileName,'r')
... text=f.read()
... f.close()
... except os.error:
... print("error in "+fileName)
...


error in /home/soumi/osmodule.txt


Output:


2. os.strerror

os.strerror() method in Python is used to get the error message corresponding to the error code.

Syntax: os.strerror(code)

Parameter: code: A integer value that denotes the error code

Return Type: This method returns a string representing the error message corresponding to the specified error code.


Type the following code in your IDE:

>>> code=1
>>> error=os.strerror(code)
>>> print("Error message corresponding to error code % d:" % code, error)
Error message corresponding to error code
1: Operation not permitted
>>> code=5
>>> error=os.strerror(code)
>>> print("Error message corresponding to error code % d:" % code, error)
Error message corresponding to error code
5: Input/output error
>>> code=3
>>> error=os.strerror(code)
>>> print("Error message corresponding to error code % d:" % code, error)
Error message corresponding to error code
3: No such process
>>> code=2
>>> error=os.strerror(code)
>>> print("Error message corresponding to error code % d:" % code, error)
Error message corresponding to error code
2: No such file or directory
>>> code=4
>>> error=os.strerror(code)
>>> print("Error message corresponding to error code % d:" % code, error)
Error message corresponding to error code
4: Interrupted system call
>>>

Output:




Click here to go to the Article on Working with directories with os module functions.

Click here to go the next article.


Thanks for viewing the article, please like and subscribe!