Is it necessary to use with to open a file?

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.

REFs:
https://docs.python.org/3/tutorial/inputoutput.html
https://www.novixys.com/blog/proper-cleanup-resources-python-using-statement/

2 Likes

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?

2 Likes

I too would like to know #get-help #faq