In programming, to manipulate file pointers in languages such as Python, the seek()
method is often used to move the file pointer to a specific position within a file. The syntax of seek()
includes parameters to specify the number of characters to move and the reference position from which to start moving.
The method call fp.seek(n, r)
is designed to move the file pointer by n
characters relative to a position r
. Here, r
can take certain values, indicating the starting point:
0
- Beginning of the file1
- Current position2
- End of the fileMoving the file pointer is a common operation in file handling, allowing reading and writing from any location within the file. Among the provided options, only fp.seek(n, r)
correctly specifies the seek
method with both n
and r
arguments, making it the correct choice for moving the file pointer to the nth character with respect to the r position.
(1) fp.seek(r): This is incorrect because it only specifies the relative position 'r' but not the offset 'n'. 'seek' requires both an offset and a position to move the file pointer.
(2) fp.seek(n): This is also incorrect. While it specifies the offset 'n', it does not specify the reference position from which to seek. The 'seek' function needs a reference point.
(3) fp.seek(n, r): This is the correct syntax. It takes the file pointer to the 'n'th character with respect to the 'r' position. 'n' is the offset, and 'r' is the reference position (0: beginning, 1: current, 2: end).
(4) seek(n,r).fp: This is incorrect because the file pointer should come first when calling the function.
Therefore, the correct method is (3) fp.seek(n, r).
List-I | List-II |
(A) readline() | (I) Writes a sequence of strings to the file |
(B) writelines() | (II) Reads a single line from the file |
(C) seek() | (III) Force any buffered output to be written to the file |
(D) flush() | (IV) Moves the file pointer to the specified position |