Read a File, or a Default

Easy ⏱ 8 min 84% acceptance ★★★★★ 4.6
Write read_or_default(path, default) that returns the file's full text if it exists, else the default string — without letting FileNotFoundError escape. Use os.path.exists (or catch the exception; either is acceptable, pick one and be consistent).

Examples

Example 1
Input
read_or_default('missing.txt', 'n/a')
Output
'n/a'
Explanation

The file is absent so the default is returned.

Constraints

  • Never raise for a missing file.
  • Return the full content otherwise.

Topics

File Handlingexistence check

Companies

ServiceNowOracle

Hints

Hint 1

os.path.exists(path) answers the question up front.

Hint 2

try/except FileNotFoundError is the EAFP alternative.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.