Introduction:
File manipulation is a crucial skill for programmers working with data and files. In this tutorial, we delve into the seek() and tell() methods in Python, which allow you to navigate and extract data from files with precision. Through a practical example, you’ll learn how to move a file object, set its position, and retrieve content efficiently.
Code:
print("Learning to move the file object")
fobject = open("testfile.txt", "r+")
str = fobject.read()
print(str)
print("Initially, the position of the file object is: ", fobject.tell())
# Seek back to the beginning of the file before reading again
fobject.seek(0)
print("Now the file object is at the beginning of the file: ", fobject.tell())
fobject.seek(10)
print("We are moving to the 10th byte position from the beginning of the file")
print("The position of the file object is at", fobject.tell())
str = fobject.read()
print(str)
fobject.close()
Logic:
- Display “Learning to move the file object” to set the context for the code.
- Open the file “testfile.txt” in read and write mode (“r+”), and assign the file object to fobject.
- Read the entire content of the file using the read() method and store it in the variable str.
- Print the content of the file (str).
- Use the tell() method to determine the current position of the file object and print it as “Initially, the position of the file object is: “.
- Use the seek(0) method to move the file object’s position back to the beginning of the file.
- Print the new position of the file object using the tell() method, indicating “Now the file object is at the beginning of the file: “.
- Use the seek(10) method to move the file object’s position to the 10th byte from the beginning of the file.
- Print the new position of the file object using the tell() method as “We are moving to the 10th byte position from the beginning of the file”.
- Read the content from the current position of the file object using the read() method and store it in the variable str.
- Print the content extracted from the file (str).
- Close the file using the close() method
Output:
>>Learning to move the file object
>>roll_numbers = [1, 2, 3, 4, 5, 6]
>> Initially, the position of the file object is: 33
>> Now the file object is at the beginning of the file: 0
> We are moving to the 10th byte position from the beginning of the file
>> The position of the file object is at 10 >> rs = [1, 2, 3, 4, 5, 6]