Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #196391
| From | Lawrence D'Oliveiro <ldo@nz.invalid> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: Best use of "open" context manager (Posting On Python-List Prohibited) |
| Date | 2024-07-07 03:49 +0000 |
| Organization | A noiseless patient Spider |
| Message-ID | <v6d38o$6dlv$3@dont-email.me> (permalink) |
| References | <mailman.3.1720263159.2981.python-list@python.org> <file-20240706124604@ram.dialup.fu-berlin.de> |
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).
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
Best use of "open" context manager Rob Cliffe <rob.cliffe@btinternet.com> - 2024-07-06 11:49 +0100 Re: Best use of "open" context manager (Posting On Python-List Prohibited) Lawrence D'Oliveiro <ldo@nz.invalid> - 2024-07-07 03:49 +0000
csiph-web