Dhanaseelan V
Dhanaseelan V

Reputation: 19

Python Seek Function with an offset exceeding the file size

I am trying to understand how the seek function in python file handling works. The syntax of this function is seek(offset, whence). The parameter 'whence' is like a point of reference with possible values 0,1 and 2 referring to start of the file, current position of the pointer (return value of 'tell' function) and end of the file respectively. Consider the file is being opened in binary red mode and the length of the file is 22. Consider three programs where I try to move the pointer to a position exceeding the file size. Logically the program should either return an exception or stop at the end of file. But the output is different where the pointer exceeds the boundary and when trying to read from that position the output is an empty string. Explain how it works.

I tried these three programs and was confused with the output.

Program 1

whence value is 0 and offset is greater than size of file

fp = open('sample.txt', 'rb')
print('Current position of pointer is', fp.tell())
size_of_file = len(fp.read())
print('Size of the file is', size_of_file)
fp.seek(0,0) #Bringing back the pointer to start of file
fp.seek(size_of_file + 1, 0)
print('Current position of pointer is', fp.tell())
print(fp.read())

The output is

Current position of pointer is 0
Size of the file is 22
Current position of pointer is 23
b''

Program 2

whence value is 1 and offset is greater than the remaining read size of the file

fp = open('sample.txt', 'rb')
print('Current position of pointer is', fp.tell())
size_of_file = len(fp.read())
print('Size of the file is', size_of_file)
fp.seek(size_of_file // 2,1) #Bringing the pointer to middle of file
fp.seek((size_of_file // 2) + 1, 1)
print('Current position of pointer is', fp.tell())
print(fp.read())

The output is

Current position of pointer is 0
Size of the file is 22
Current position of pointer is 45
b''

Program 3

whence value is 2 and offset is a positive number

fp = open('sample.txt', 'rb')
print('Current position of pointer is', fp.tell())
size_of_file = len(fp.read())
print('Size of the file is', size_of_file)
fp.seek(0,2) #Bringing the pointer to end of file
fp.seek(1, 2)
print('Current position of pointer is', fp.tell())
print(fp.read())

The output is

Current position of pointer is 0
Size of the file is 22
Current position of pointer is 23
b''

Explain how the pointer moves?

Upvotes: 1

Views: 284

Answers (1)

Mehmet Ali Öden
Mehmet Ali Öden

Reputation: 111

when you attempt to seek beyond the end of a file in Python, the file pointer is positioned at the end of the file. Subsequent read operations from this position return an empty string, indicating the end of the file has been reached. This behavior allows for seeking beyond the end of the file without raising exceptions, providing flexibility in file manipulation.

Upvotes: 0

Related Questions