0

I'm looking to use xarray.openmfdataset to open a specific set of files. For example, I'd like to open file.20180101.nc, file.20180102.nc, file20180103.nc with the following code:

xr.open_mfdataset('./file.{20180101..20180103}.nc', combine='by_coords')

The beginning and end integers are stored in variables ts and te, so I'd ideally like to use an fstring like this:

xr.open_mfdataset('./file.\{{ts}..{te}\}.nc', combine='by_coords')

Where the '{}' that don't contain a variable are escaped out. However, I get the following error: SyntaxError: f-string: single '}' is not allowed

A quick search didn't show any solution to this, is there a good way to accomplish this?

lsterzinger
  • 687
  • 5
  • 22

2 Answers2

2

bash-style brace expansion isn't a glob, and isn't supported by open_mfdataset. You can pass a list of file names, however.

xr.open_mfdataset(
    [f'./file.{x}.nc' for x in range(ts, te)],
    combine='by_coords'
)
chepner
  • 497,756
  • 71
  • 530
  • 681
1

Brackets in f-strings are escaped with more brackets. {{ is an escaped open-bracket, and }} is an escaped close-bracket.

Accordingly, this should work:

xr.open_mfdataset(f'./file.{{{ts}..{te}}}.nc', combine='by_coords')
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
  • While this answers half of the question (how to include `{}` in an fstring), as mentioned in the accepted answer `open_mfdataset` doesn't support brace expansion at all, and the accepted answer addresses this. Thanks for your input! – lsterzinger Jan 21 '20 at 20:47