Python writable() Function

The writable() function in Python, used to check whether the file is writable or not. In other words, we can say that this function is used to check whether we can write to the file or not.

Note: The file may not be writable because of many reasons such as the write operation on the file is not allowed, or the file opening mode used as r (the reading only mode) etc.

Python writable() Syntax

The syntax to use writable() function is:

fh.writable()

where fh indicates to file handler or object. It returns True if file whose handler is fh, is writable, otherwise returns False.

Python writable() Example

Let's create an example program that uses writable() function to check and print the message regarding, whether the file is writable or not:

fh = open("codescracker.txt", "w")
if fh.writable():
    print("The file \"codescracker.txt\" is writable.")
else:
    print("The file \"codescracker.txt\" is not writable.")
fh.close()

Here is its sample run:

python writable

Since the file codescracker.txt opened in w mode, therefore we can write to the file using its handler.

If you change the opening mode from w to r (reading only), then the output will be:

writable python

Note: If r mode is used while opening the file, then the open() function produces error or throws exception say FileNotFoundError. Here is an example:

try:
    fh = open("none.txt", "r")
    if fh.writable():
        print("It is writable.")
    else:
        print("It is not writable.")
except FileNotFoundError:
    print("File not found!")

Because the file none.txt does not available, therefore you'll see the output:

File not found!

Python Online Test


« Previous Function Next Function »


Liked this post? Share it!