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/

16 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

It can read any file with text content, despite the extension.
And it can read the file anywhere, but if it’s not in your working directory, then you have to specify the full path to that file

2 Likes

Hey! So… it isn’t necessary to use ‘with’ to open a file. But, it must have some other use. Can you please tell me why and where ‘with’ is used because I haven’t come across it until now when I am starting with files.

1 Like