Using 'with open(...) as ...' together with configparser.ConfigParser.read
Jon Ribbens
jon+usenet at unequivocal.eu
Tue Oct 29 11:33:57 EDT 2024
On 2024-10-29, Loris Bennett <loris.bennett at 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.
More information about the Python-list
mailing list