Python seekable method:
The seekable method of IOBase class returns True if the file is seekable. In other words, the seekable() method returns True only if random access is allowed on the file, otherwise, it returns False.
However, if we use seek(), tell(), or truncate() method on the file that is not seekable, it will raise an exception.
A file on a disk is always seekable, but the file handle abstraction does not apply only to files on a local disk. If the file handle accesses the stream like pipes or network sockets, it will not be seekable always.
Method Signature
The signature for the seekable method is as shown below.
fileObject.seekable()
Method parameters and return type
- Here, the seekable() method doesn’t take any parameter.
- However, it will return a boolean value True or False.
Python seekable method Examples:
Example 1: In this case, we will open a file in w+ mode and check if it is seekable or not.
# Opening a file
f1 = open("test.txt", "w+")
# Writing
f1.write("Hello World")
f1.write("\nPython Programming")
# Checking if file is seekable or not
print("Is file ",f1," seekable? ",f1.seekable())
# closing
f1.close()
Output
Is file <_io.TextIOWrapper name='test.txt' mode='w+' encoding='UTF-8'> seekable? True
Example 2: In this case, we will open a file in a read mode and check if it is seekable or not.
# Opening a file
f1 = open("test.txt", "r")
# Reading
print(f1.read())
# Checking if file is seekable or not
print("Is file ",f1," seekable? ",f1.seekable())
# closing
f1.close()
Output
Hello World
Python Programming
Is file <_io.TextIOWrapper name='test.txt' mode='r' encoding='UTF-8'> seekable? True
Example 3: In this case, we will open a file in an append mode and check if it is seekable or not.
# Opening a file
f1 = open("test.txt", "a+")
# Writing
f1.write("\nIt's fun to learn Programming")
# Checking if file is seekable or not
print("Is file ",f1," seekable? ",f1.seekable())
# closing
f1.close()
Output
Is file <_io.TextIOWrapper name='test.txt' mode='a+' encoding='UTF-8'> seekable? True
Conclusion
Hence, the seekable() method returns True if the file has random access, False otherwise.
References
Happy Learning 🙂