As an alternative to using the previously seen syntax to open and interact with files, we can simplify and compact the code required for this by using a with statement. For example:
# without using a with statement: f = open('file_path', 'w') f.write('hello world !') f.close() # using with statement with open('file_path', 'w') as file: file.write('hello world !')
Using a with statement simplifies the management of file streams, makes the code more readable, and allows us to “close” the file by simply exiting the indented area under the with statement. This syntax is just one alternative to what we saw in the previous file handling topic.