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.
The syntax to use writable() function is:
where fh indicates to file handler or object. It returns True if file whose handler is fh, is writable, otherwise returns False.
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:
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:
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!
© Copyright 2021. All Rights Reserved.