Search code examples
pythonf-string

Using '{a..b}' wildcard in fstring


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?


Solution

  • 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'
    )