Python writable method:

The writable is a method of IOBase class in Python. This method returns True if a file stream is writable. However, if the file stream is not writable, it will return False. If we call a write or truncate function with the file object that is not writable, it will raise an exception.

Method Signature

The signature for the writable method is as shown below.

fileObject.writable()

Method parameters and return type

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

Python writable method Examples:

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

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

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

Output

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

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

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

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

# closing
f1.close()

Output

Is file writable ? True

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

# creating a file 
f1 = open("test.txt", "r")
print("Is file writable ?",f1.writable())

# closing
f1.close()

Output

Is file writable ? False

Conclusion

Hence, the writable() method return a true value if the file is open for writing or appending, false otherwise.

References

Happy Learning 🙂

Leave A Comment