Re: Best use of "open" context manager

Liste des GroupesRevenir à cl python 
Sujet : Re: Best use of "open" context manager
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.python
Date : 06. Jul 2024, 13:46:33
Autres entêtes
Organisation : Stefan Ram
Message-ID : <file-20240706124604@ram.dialup.fu-berlin.de>
References : 1
Rob Cliffe <rob.cliffe@btinternet.com> wrote or quoted:
try:
    with open(FileName) as f:
except FileNotFoundError:
    print(f"File {FileName} not found")
    sys.exit()
else: # or "finally:"
        for ln in f:
            print("I do a lot of processing here")
            # Many lines of code here .....
but this of course does not work because by the time we get to "for ln
in f:" the file has been closed so we get
ValueError: I/O operation on closed file

try:
    f = open( FileName )
except FileNotFoundError:
    print( f"File {FileName} not found" )
    sys.exit()
else:
    with f:
        # put this into a separate function if it gets too long here.
        for ln in f:
            print( "I do a lot of processing here" )
            # Many lines of code here .....

Date Sujet#  Auteur
6 Jul 24 * Best use of "open" context manager3Rob Cliffe
6 Jul 24 `* Re: Best use of "open" context manager2Stefan Ram
7 Jul 24  `- Re: Best use of "open" context manager (Posting On Python-List Prohibited)1Lawrence D'Oliveiro

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal