Python File seekable() Method – Tutorial with Examples

Python File seekable() Method

The seekable() method in Python is a built-in method used to check whether the file is seekable or not. It returns True if the file is seekable and False otherwise. The file is considered seekable if it has a file descriptor and is opened in a mode that allows the file position to be changed.

Syntax

file.seekable()

Return Value

The seekable() method returns True if the file is seekable and False otherwise.

Examples

Example 1: Check if the file is seekable or not

In this example, we will use the seekable() method to check whether a file is seekable or not:

file1 = open("example.txt", "r")
print(file1.seekable())
file1.close()
file2 = open("example2.txt", "a")
print(file2.seekable())
file2.close()

In this example, we opened two files “example.txt” and “example2.txt” in read and append mode respectively. We then used the seekable() method to check whether the files are seekable or not.

Output:

True
False

Example 2: Check if the standard input/output streams are seekable

In this example, we will use the seekable() method to check whether the standard input/output streams are seekable or not:

import sys
print(sys.stdin.seekable())
print(sys.stdout.seekable())
print(sys.stderr.seekable())

In this example, we imported the sys module and used the seekable() method to check whether the standard input/output streams are seekable or not.

Output:

False
True
False

Example 3: Check if a BytesIO object is seekable

In this example, we will use the seekable() method to check whether a BytesIO object is seekable or not:

import io
file = io.BytesIO(b"Hello, World!")
print(file.seekable())
file.close()

In this example, we created a BytesIO object containing the bytes “Hello, World!” and used the seekable() method to check whether the object is seekable or not.

Output:

True

Use Cases

  • The seekable() method can be used to check whether a file is seekable or not before attempting to change the position of the file pointer using the seek() method.
  • The seekable() method can be used to check whether the standard input/output streams are seekable or not, which can be useful in certain situations where seekability is required.
  • The seekable() method can be used to check whether a file-like object is seekable or not before attempting to perform operations that require seeking, such as reading or writing at specific positions in the object.

Conclusion

The seekable() method in Python is a useful built-in method for checking whether a file or file-like object is seekable or not. It can be used to avoid errors that may occur when attempting to perform operations that require seeking on non-seekable objects. It is a simple method to use and can save a lot of time and effort when working with files and file-like objects.

Leave a Reply

Your email address will not be published. Required fields are marked *