Using the 'with' keyword
It is good practise to open files you want to use using the with keyword. This is because your files may not close properly if your program has a bug or terminates all of a sudden. When you put your code for opening and working with a file inside 'with' block, a file close method is automatically carried out, however the program terminates. Now we know how to open files from reading, we need to ensure we start using 'with'.
Q1. Type this code in and run it:
with open('haiku.txt','r',encoding='utf-8') as poem:
print(poem.read())
What does the above code do?
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()
What does the above program do?
Q3. As you can see from the above, using the with keyword is very simple and doesn't really change anything. All we have to do is:
type the with keyword and then type open followed by the path, access mode and encoding, then type the keyword as and then type whatever we are going to call the file object. We then need a colon. All code after that is indented in the with block. We don't need to use a close() because one happens automatically we exit the with block.
Go back through all of your programs and modify them so that they all use a with statement. Make sure you test each one. From now on, all file access programs you write will use 'with'.