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?
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
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.
Hello @py3711976494 and welcome to the forums!
with keyword closes the file after the code block has been run. See Python’s documentation here for more.
2 posts were split to a new topic: Is it necessary to use ‘as’