Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #196997

Re: FileNotFoundError thrown due to file name in file, rather than file itself

From Cameron Simpson <cs@cskk.id.au>
Newsgroups comp.lang.python
Subject Re: FileNotFoundError thrown due to file name in file, rather than file itself
Date 2024-11-12 08:17 +1100
Message-ID <mailman.94.1731359879.4695.python-list@python.org> (permalink)
References <26418.15836.335097.984240@ixdm.fritz.box> <ZzJ0eoWZds3xSKWn@cskk.homeip.net>

Show all headers | View raw


On 11Nov2024 18:24, dieter.maurer@online.de <dieter.maurer@online.de> wrote:
>Loris Bennett wrote at 2024-11-11 15:05 +0100:
>>I have the following in my program:
>>    try:
>>        logging.config.fileConfig(args.config_file)
>>        config = configparser.ConfigParser()
>>        config.read(args.config_file)
>>        if args.verbose:
>>            print(f"Configuration file: {args.config_file}")
>>    except FileNotFoundError:
>>        print(f"Error: configuration file {args.config_file} not found.  Exiting.")
>
>Do not replace full error information (including a traceback)
>with your own reduced error message.
>If you omit your "try ... except FileNotFoundError`
>(or start the `except` clause with a `raise`), you
>will learn where in the code the exception has been raised
>and likely as well what was not found (Python is quite good
>with such error details).

Actually, file-not-found is pretty well defined - the except action 
itself is fine in that regard.

[...]
>>2. In terms of generating a helpful error message, how should one
>>   distinguish between the config file not existing and the log file not
>>   existing?

Generally you should put a try/except around the smallest possible piece 
of code. So:

     config = configparser.ConfigParser()
     try:
         config.read(args.config_file)
     except FileNotFoundError as e:
         print(f"Error: configuration file {args.config_file} not found: {e}")

This way you know that the config file was missing.

Cheers,
Cameron Simpson <cs@cskk.id.au>

Back to comp.lang.python | Previous | NextNext in thread | Find similar


Thread

Re: FileNotFoundError thrown due to file name in file, rather than file itself Cameron Simpson <cs@cskk.id.au> - 2024-11-12 08:17 +1100
  Re: FileNotFoundError thrown due to file name in file, rather than file itself "Loris Bennett" <loris.bennett@fu-berlin.de> - 2024-11-12 09:52 +0100
    Re: FileNotFoundError thrown due to file name in file, rather than file itself Karsten Hilbert <Karsten.Hilbert@gmx.net> - 2024-11-12 18:47 +0100
    Re: FileNotFoundError thrown due to file name in file, rather than file itself Rob Cliffe <rob.cliffe@btinternet.com> - 2024-11-12 21:04 +0000

csiph-web