Back

The seek and tell methods - Answers

Q1. Assuming you have your haiku.txt poem in the same folder as where you will save this Python program, get this code into Python:

# A program to demonstrate reading and writing
# from and to files.

poem = open('haiku.txt','r',encoding='utf-8')
print(poem.tell())
print(poem.read())
print(poem.tell())
print(poem.read())
poem.close()

I want to print out the poem twice using print(poem.read()) but the second time I use this statement, it just prints out the empty string. When you open a file object, there is an index immediately created as well. The index is used to tell Python what character to print next. To start with, it points to the first character, which is index value 0, and prints that one. As each character is printed, the index is increased by 1 (incremented). After Python printed all the characters, the index was pointing past the last character, character 131. When Python tried to print the poem for a second time, there was nothing left to print because we were at the end of the file so Python just printed the empty string. The tell() method is used to tell you where the index is currently pointing.

Q2. The seek method can take up to two arguments: seek(offset, from_position). In the above example, I didn't include the from_position so the index defaulted to the start of the file. It then added a number (the offset) to the index to get the new index position.
Q3. The seek method can take up to two arguments: seek(offset, from_position). In the above example, I didn't include the from_position so the index defaulted to the start of the file. It then added a number (the offset) to the index to get the new index position). Suppose, however, that I wanted to print from the fourth character the second time around. Modify your program so it looks like this:

# A program to demonstrate reading and writing
# from and to files.
poem = open('haiku.txt','r',encoding='utf-8')
print(poem.tell())
print(poem.read())

print(poem.seek(3,0))
print(poem.read())
poem.close()

The seek() method is used to move the file object's index. The second time around, seek moved the index to the beginning (so it was at position 0 and pointing to the first character).  and then added 3 to this (so the index was pointing to the fourth character). When Python started to print, it now printed starting from old

Q4 - Q5. Practise the same skills.

Back