Using the 'with' keyword - Answers
Teachers should explain that it is good practice to enclose all file operations inside a with block, and give an example of using a with block.
Q1. Type this code in and run it:
with open('haiku.txt','r',encoding='utf-8') as poem:
print(poem.read())
This code prints out the poem.
Q2. Type this code in and run it:
with open('haiku.txt','r',encoding='utf-8') as poem:
poem.seek(9,0)
print(poem.read(20))
poem.close()
This code prints out 20 characters starting from character 10.
Q3. Practise using with. Start by revisiting all programs done so far and modifying them. Ensure they are tested as they are modified.