Sujet : Re: FileNotFoundError thrown due to file name in file, rather than file itself
De : Karsten.Hilbert (at) *nospam* gmx.net (Karsten Hilbert)
Groupes : comp.lang.pythonDate : 12. Nov 2024, 18:47:37
Autres entêtes
Message-ID : <mailman.99.1731433661.4695.python-list@python.org>
References : 1 2 3 4 5
Am Tue, Nov 12, 2024 at 09:52:31AM +0100 schrieb Loris Bennett via Python-list:
Regarding your example above, if 'missingfile.py' contains the following
>
import configparser
>
config = configparser.ConfigParser()
>
try:
config.read('/foo/bar')
except FileNotFoundError as e:
print(f"Error: configuration file {config_file} not found: {e}")
>
them
>
python3 missingfile.py
>
does not produce an any output for me and so does not seem to be a
reliable way of handling the case where the config file does not exist.
Well:
>>> help(config.read)
Help on method read in module configparser:
read(filenames, encoding=None) method of configparser.ConfigParser instance
Read and parse a filename or an iterable of filenames.
Files that cannot be opened are silently ignored; this is
designed so that you can specify an iterable of potential
configuration file locations (e.g. current directory, user's
home directory, systemwide directory), and all existing
configuration files in the iterable will be read. A single
filename may also be given.
Return list of successfully read files.
So, the very fact that it does not return any output AND
returns an empty list is the (intended) way of knowing the
error state.
Karsten
-- GPG 40BE 5B0E C98E 1713 AFA6 5BC0 3BEA AC80 7D4F C89B