So far, we discussed different flags that could be used to open files in different modes. The examples we discussed followed a common pattern—open the file, perform read/write operations and close the file. There is an elegant way of interacting with files using the with keyword.
If there are any errors during the execution of the code block that interacts with a file, the with keyword ensures that the file is closed and the associated resources are cleaned up on exiting the code block. As always, let's review the with keyword with an example:
if __name__ == "__main__":
with open('write_file.txt', 'r+') as file:
# read the contents of the file and print to the screen
print(file.read())
file.write("This is a line appended to the file")
#rewind the file and read its contents
file.seek(0)
print(file.read())
# the file is automatically closed at this point
print("Exited the with keyword code block")
In the preceding example (with_keyword_example), we skipped closing the file as the with keyword takes care of closing the file once the execution of the indented code block is complete. The with keyword also takes care of closing the file while leaving the code block due to an error. This ensures that the resources are cleaned up properly in any scenario. Going forward, we will be using the with keyword for file I/O.