Move the File Pointer Using seek() in Python

In Python, the seek() method is used to move the file pointer to a specific position within a file. This allows reading or writing from a particular location instead of starting from the beginning or end of the file. The seek() method takes two arguments: the offset (number of bytes to move) and the whence (reference position from where to move).


Examples

1. Moving the File Pointer to the Beginning

In this example, we use seek(0) to move the file pointer back to the beginning of the file and read the contents again.

main.py

</>
Copy
# Opening a file in read mode
with open("sample.txt", "r") as file:
    # Reading and displaying the first 10 characters
    content = file.read(10)
    print("First Read:", content)

    # Moving the file pointer to the beginning
    file.seek(0)

    # Reading again from the beginning
    content = file.read(10)
    print("Second Read:", content)

Explanation:

  1. The file sample.txt is opened in read mode.
  2. The read(10) function reads the first 10 characters.
  3. The seek(0) function moves the pointer back to the start.
  4. Reading again with read(10) gives the same output as the first read.

Output:

2. Moving the File Pointer to a Specific Position

We can use seek(n) to move the file pointer to a specific byte position.

In this example, we open sample.txt, seek the file pointer to position 6, and then read five characters from the file pointer position.

main.py

</>
Copy
# Opening a file in read mode
with open("sample.txt", "r") as file:
    # Moving the file pointer to the 6th byte
    file.seek(6)

    # Reading the next 5 characters
    content = file.read(5)
    print("Read after seek:", content)

Explanation:

  1. The file is opened in read mode.
  2. The seek(6) function moves the pointer to the 6th byte.
  3. The read(5) function then reads 5 characters from that position.

Output:

3. Moving the File Pointer to the End

By using seek(0, 2), we move the file pointer to the end of the file.

main.py

</>
Copy
# Opening a file in read mode
with open("sample.txt", "r") as file:
    # Moving the file pointer to the end
    file.seek(0, 2)

    # Getting the current position (file size)
    position = file.tell()
    print("File size:", position)

Explanation:

  1. The file is opened in read mode.
  2. The seek(0, 2) function moves the pointer to the end.
  3. The tell() function retrieves the current position, which is the file size.

Output:

Conclusion

In this tutorial, we used the seek() function with the following scenarios:

  1. seek(0): Moves the pointer to the beginning.
  2. seek(n): Moves the pointer to byte n.
  3. seek(0, 2): Moves the pointer to the end.