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
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
573 PHP ssh2_scp_send fails to send files as intended
865 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
564 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
593 Uncaught (inpromise) Error on Electron: An object could not be cloned
© 2024 OneMinuteCode. All rights reserved.