Is it necessary to use ‘with’ to open a file?
Alternatively, one could write the code as follows.
text_file = open('welcome.txt') text_data = text_file.read() print(text_data) text_file.close()
Under normal bug-free circumstances, the close method is used to free up resources, but it doesn’t handle exceptions.
The benefit of with…as is that you create a block that handles resource cleanup regardless of whether an exception occurred or not.
Hi, I have two questions!
Does it have to be a .txt file?
Does the file have to be in the working directory in order to open it?