Re: Best use of "open" context manager

Liste des GroupesRevenir à cl python 
Sujet : Re: Best use of "open" context manager
De : cs (at) *nospam* cskk.id.au (Cameron Simpson)
Groupes : comp.lang.python
Date : 07. Jul 2024, 03:08:33
Autres entêtes
Message-ID : <mailman.10.1720315042.2981.python-list@python.org>
References : 1 2
User-Agent : Mutt/2.2.13 (2024-03-09)
On 06Jul2024 11:49, Rob Cliffe <rob.cliffe@btinternet.com> wrote:
try:
    f = open(FileName) as f:
    FileLines = f.readlines()
except FileNotFoundError:
    print(f"File {FileName} not found")
    sys.exit()
# I forgot to put "f.close()" here -:)
for ln in File Lines:
        print("I do a lot of processing here")
        # Many lines of code here .....
What about this:
     try:
         f = open(FileName) as f:
     except FileNotFoundError:
         print(f"File {FileName} not found")
         sys.exit()
     with f:
         ... process the lines here ...
Remember, the `open()` call returns a file object _which can be used as a context manager_. It is separate from the `with` itself.

Date Sujet#  Auteur
7 Jul 24 o Re: Best use of "open" context manager1Cameron Simpson

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal