Python readable method:

The readable is a method of IOBase class in Python. This method returns True if a file stream is readable. However, if the file stream is not readable, it will return False. If we call a read function with the file object that is not readable, it will raise an exception. The file is readable in only r mode, w+ mode and a+ mode.

Method Signature

The signature for the readable() method is as shown below.

fileObject.readable()

Method parameters and return type

  • Here, the readable method doesn’t take any parameters.
  • However, it returns a boolean value True or False.

Python readable method Examples:

Example 1: In this case, we will open a file in write mode and check if it is readable or not.

# creating a file 
f1 = open("test.txt", "w")

# Writing 
f1.write("Hello World")
f1.write("\nPython Programming")
print("Is file readable ?",f1.readable())
#Trying to read
print(f1.read())
# closing
f1.close()

Output

Is file readable ? False
Traceback (most recent call last):
  File "main.py", line 7, in 
    print(f1.read())
io.UnsupportedOperation: not readable

Example 2: In this case, we will open a file in w+ mode and check if it is readable or not.

# creating a file 
f1 = open("test.txt", "w+")

# Writing 
f1.write("Hello World")
f1.write("\nPython Programming")
print("Is file readable ?",f1.readable())

# closing
f1.close()

Output

Is file readable ? True

Example 3: In this case, we will open a file in append mode and check if it is readable or not.

# creating a file 
f1 = open("test.txt", "a")

# Writing 
f1.write("Its fun to learn Programming")
print("Is file readable ?",f1.readable())

# closing
f1.close()

Output

Is file readable ? False

Conclusion

Hence, the readable() method return a true value if the file is open for reading, false otherwise.

References

Happy Learning 🙂