Q.Consider the following Python statement: F=open('CONTENT.TXT') Which of the following is an invalid statement in Python? (A) F.seek(1,0) (B) F.seek(0,1) (C) F.seek(0,-1) (D) F.seek(0,2)
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →The seek() method in Python's file handling allows you to change the current position of the file pointer, but its whence argument, which specifies the reference point, must be one of three specific integer values: 0 (beginning), 1 (current position), or 2 (end of file).
In Python, interacting with files is a fundamental aspect of many programs, allowing us to store and retrieve data persistently. The statement F = open('CONTENT.TXT') is the first step in this process. It opens a file named CONTENT.TXT in the default read mode ('r') and returns a file object, which we've assigned to the variable F. This file object acts as a gateway, providing methods to perform operations like reading, writing, and, importantly, navigating within the file.
One crucial method for navigating within a file is seek(). Imagine a cursor in a text editor; seek() allows you to move this cursor to a specific location within the file. This is incredibly useful when you need to re-read a part of a file, skip certain sections, or write data at a precise point.
The seek() method takes two arguments: seek(offset, whence).
- The
offsetargument specifies the number of bytes to move. This can be a positive or negative integer, depending on thewhenceargument. - The
whenceargument determines the reference point from which theoffsetis calculated. This is where the strict rules apply, and understanding these values is key to usingseek()correctly.
There are only three valid integer values for whence:
0(oros.SEEK_SET): This means theoffsetis relative to the beginning of the file. Whenwhenceis 0, theoffsetmust be a non-negative integer, as you cannot move before the start of the file.1(oros.SEEK_CUR): This means theoffsetis relative to the current file position. Theoffsetcan be positive (to move forward) or negative (to move backward) from the current position.2(oros.SEEK_END): This means theoffsetis relative to the end of the file. Whenwhenceis 2, theoffsetis typically a non-positive integer (0 or negative) to move backward from the end of the file. A positive offset from the end would move beyond the file's actual content.
The whence argument in F.seek(offset, whence) can only take the integer values 0, 1, or 2. Any other integer value will result in an OSError or ValueError.
Now, let's examine the given statements based on these rules: …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.