What is the difference between open() and with statement when reading a file?

Asked 2 years ago, Updated 2 years ago, 93 views

When reading a file, We usually use open("filename", "r") or with open("filename") as file Is there a big difference between the two? on a foreign site It(with statement) is designed to provide much cleaner syntax and exceptions handling when you are working with code. It says so, but is there any difference other than this?

open file with

2022-09-22 13:10

1 Answers

If with statement is used in python, the context manager determines the object's content It automatically invokes _enter__(), __exit_() to ensure that it is cleaned up properly if an exception occurs or the developer forgets to release the resource by mistake.

This means that you can get the same effect as using try/exception/finally explicitly.

If you just used open("filename", "r"), you must close the file after you use it.

However, _enter__(), __exit_() is implemented in the file object, so using with statement is convenient because close is self-evident when you exit the with block after using the file object.

When you ask questions, please specify at least the language you currently use :D


2022-09-22 13:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.