Deutsch English Français Italiano |
<87bjz1vj2c.fsf@zedat.fu-berlin.de> View for Bookmarking (what is this?) Look up another Usenet article |
Path: ...!feeds.phibee-telecom.net!2.eu.feeder.erje.net!feeder.erje.net!fu-berlin.de!uni-berlin.de!not-for-mail From: "Loris Bennett" <loris.bennett@fu-berlin.de> Newsgroups: comp.lang.python Subject: Re: Using 'with open(...) as ...' together with configparser.ConfigParser.read Date: Wed, 30 Oct 2024 14:03:55 +0100 Organization: FUB-IT, Freie =?utf-8?Q?Universit=C3=A4t?= Berlin Lines: 65 Message-ID: <87bjz1vj2c.fsf@zedat.fu-berlin.de> References: <87plnj3te6.fsf@zedat.fu-berlin.de> <slrnvi2035.372.jon+usenet@raven.unequivocal.eu> Mime-Version: 1.0 Content-Type: text/plain X-Trace: news.uni-berlin.de R/g7l+LNrQYMfsIF9iHcHgx1MxdSRRKE+//oTuT66VRPvh Cancel-Lock: sha1:77rJOTJcLRAyDM2SJe+klrkcYm0= sha1:kDXkrpFG0nPZ5Kz8WxXHHfypq08= sha256:AEYBlnxLQ+t8RQrtXzkZyShPSTaMYMiq+pZ2nZLb+rA= User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/28.2 (gnu/linux) Bytes: 2870 Jon Ribbens <jon+usenet@unequivocal.eu> writes: > On 2024-10-29, Loris Bennett <loris.bennett@fu-berlin.de> wrote: >> Hi, >> >> With Python 3.9.18, if I do >> >> try: >> with open(args.config_file, 'r') as config_file: >> config = configparser.ConfigParser() >> config.read(config_file) >> print(config.sections()) >> >> i.e try to read the configuration with the variable defined via 'with >> ... as', I get >> >> [] >> >> whereas if I use the file name directly >> >> try: >> with open(args.config_file, 'r') as config_file: >> config = configparser.ConfigParser() >> config.read(args.config_file) >> print(config.sections()) >> I get >> >> ['loggers', 'handlers', 'formatters', 'logger_root', 'handler_fileHandler', 'handler_consoleHandler', 'formatter_defaultFormatter'] >> >> which is what I expect. >> >> If I print type of 'config_file' I get >> >> <class '_io.TextIOWrapper'> >> >> whereas 'args.config_file' is just >> >> <class 'str'> >> >> Should I be able to use the '_io.TextIOWrapper' object variable here? If so how? >> >> Here >> >> https://docs.python.org/3.9/library/configparser.html >> >> there are examples which use the 'with open ... as' variable for writing >> a configuration file, but not for reading one. > > As per the docs you link to, the read() method only takes filename(s) > as arguments, if you have an already-open file you want to read then > you should use the read_file() method instead. As you and others have pointed out, this is indeed covered in the docs, so mea culpa. However, whereas I can see why you might want to read the config from a dict or a string, what would be a use case in which I would want to read from an open file rather than just reading from a file(name)? Cheers, Loris -- This signature is currently under constuction.