Re: Best use of "open" context manager

Liste des GroupesRevenir à cl python 
Sujet : Re: Best use of "open" context manager
De : Richard (at) *nospam* Damon-Family.org (Richard Damon)
Groupes : comp.lang.python
Date : 06. Jul 2024, 17:01:11
Autres entêtes
Message-ID : <mailman.8.1720278854.2981.python-list@python.org>
References : 1 2
User-Agent : Mozilla Thunderbird
My thoughts is that if the "many lines of code" puts the except to far
from the try, then perhaps it would have made sense to factor out some
part there into a function.
Perhaps like:
try:
    with open(FileName) as f:
       for ln in f{
          process(ln)
except FileNotFoundError:
    print(f"File {FileName} not found:")
    sys.exit()
Now the "process" function has been factored out and can be well
documented as to what it is doing on each line, and this code can be
documented as running process on each line of the file.
On 7/6/24 6:49 AM, Rob Cliffe via Python-list wrote:
Consider this scenario (which I ran into in real life):
    I want to open a text file and do a lot of processing on the lines
of that file.
    If the file does not exist I want to take appropriate action, e.g.
print an error message and abort the program.
I might write it like this:
>
try:
    with open(FileName) as f:
        for ln in f:
            print("I do a lot of processing here")
            # Many lines of code here .....
except FileNotFoundError:
    print(f"File {FileName} not found")
    sys.exit()
>
but this violates the principle that a "try" suite should be kept
small, so that only targeted exceptions are trapped,
not to mention that having "try" and "except" far apart decreases
readability.
>
Or I might write it like this:
>
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 .....
>
but this loses the benefits of using "open" as a context manager,
and would also be unacceptable if the file was too large to read into
memory.
>
Really I would like to write something like
>
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
>
I could modify the last attempt to open the file twice, which would
work, but seems like a kludge (subject to race condition, inefficient).
>
Is there a better / more Pythonic solution?
>
Best wishes
Rob Cliffe
--
Richard Damon

Date Sujet#  Auteur
6 Jul 24 o Re: Best use of "open" context manager1Richard Damon

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal