The seek and tell methods
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. Can you think of a reason why? What does the tell() method do?
Q2. 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.
All is not lost, however! You can move the index pointer around using the seek() method. Modify your program so it looks like the following:
# 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(0))
print(poem.read())
poem.close()
What happens now? Describe what seek() does.
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 second time around, seek moves the index to the beginning (so it is position 0 and pointing to the first character) and then adds 3 to this (so index is now pointing to the fourth character). When you start to print, you now print starting from old. Experiment with different offsets.
Q4. Using a poem of your own, print it out twice using the read() method combined with the seek() method.
Q5. Experiment with how much you print out the second time around by using the offset in the seek() method.