Re: Best use of "open" context manager (Posting On Python-List Prohibited)

Liste des GroupesRevenir à cl python 
Sujet : Re: Best use of "open" context manager (Posting On Python-List Prohibited)
De : ldo (at) *nospam* nz.invalid (Lawrence D'Oliveiro)
Groupes : comp.lang.python
Date : 07. Jul 2024, 05:49:44
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v6d38o$6dlv$3@dont-email.me>
References : 1 2
User-Agent : Pan/0.158 (Avdiivka; )
On 6 Jul 2024 11:46:33 GMT, Stefan Ram wrote:

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 .....

    f = open(filename, "rt")
    for ln in f :
        ... do your processing ...

1) Let the error exception be reported directly, whether it’s “file not
found”, or “permission error”, or some other reason; why bother to handle
it when you don’t even know what to do anyway?
2) Notice that a file open for reading automatically gets closed when it
goes out of scope (feature of CPython and all the other good
implementations).

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