Reading csv file, with fallback

Hi

I’m trying to read a csv-file and the actions taken after this depends on whether there is a csv-file or not.

try:
    temp = pl.read_parquet("test.parquet")
    do some super cool other stuff
    do some additional things
    etc... 
except:
    temp = temp = pl.read_parquet("fallback.parquet")

How is this done in Python? Try to read a file, if the file doesn’t exist read a fallback file?

What is the problem you’re experiencing?

What you’ve got looks like it should work. I’d probably format it more like

test_file = Path(...)
fallback = Path(...)
if test_file.exists():
  temp = pl.read_csv(test_file)
else:
  temp = pl.read_csv(fallback)

but the following is also a perfectly valid pattern:

try:
  temp = pl.read_parquet(test_file)
  [some post processing]
except ComputeError:
  temp = pl.read_parquet(fallback)
[most of the code]

A lot like this, but:

  • with a specific exception, not a “bare except”
  • with the try/except around only the read_parquet call

So something like:

 try:
     temp = pl.read_parquet("test.parquet")
 except FileNotFoundError:
     temp = pl.read_parquet("fallback.parquet")
 do stuff here

We try to avoid “bare” excepts because they catch everything.
Permission errors (file exists but you can’t read it), name errors
(you’ve misspelled a variable name) etc etc. A try/except should catch
only the precise circumstance which you’re accomodating. Here that is
a missing file, and there’s a specific exception for that.

We also try to keep the try/except body as short as possible. That way
you know what the exception came from. As opposed to sme exception from
your additional things.

Thanks for the input!

I ended up looking for the file as Gerlagn suggested, thanks!