Understanding the Elements of Python with Statements

Asked 2 years ago, Updated 2 years ago, 18 views

I can't ask the right question because I don't know what the problem is, but I don't know the structure of the code written using the following with statement.
The following is a pseudo code.

import gzip
import codecs

with codecs.getreader('utf-8') (gzip.open(u'inputfile.gz', 'r') as f:
    for line inf:
        some processes

(This example has Problem 20 in mind with 100 knocks on language processing)
What does gzip.open() have to do with codecs.getreader() in this with statement?
In other words, gzip.open() is not a codecs method, nor is it in the scope of .getreader, so I think it's probably one of the elements of the with statement, but I don't know what it is. If the with statement can take many elements (sections?) in parallel, what is their relationship?

python

2022-09-30 18:24

2 Answers

If you don't mind the exceptions

f=codecs.getreader('utf-8') (gzip.open(u'inputfile.gz', 'r')))
for line inf:
    some processes
f.close()

with is irrelevant.

See Python document

codecs.getreader(encoding) Finds codec for the given encoding and returns a StreamReader class or factory function.

Therefore, the value returned by codecs.getreader can be called as a function.Therefore, the first line is further

 factory=codecs.getreader('utf-8')
gzippeddata=gzip.open(u'inputfile.gz', 'r')
f=factory(gzippeddata)

can be written as .In other words, codecs.getreader('utf-8')(gzip.open(u'inputfile.gz','r') is a continuous function call.

Syntaxes such as f()() typically invoke functions continuously.


2022-09-30 18:24

I think that's what it is.

import gzip
import codecs

myreader=codecs.getreader('utf-8')
with myreader(gzip.open(u'inputfile.gz', 'r') as f:
    for line inf:
        some processes


2022-09-30 18:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.