I have an interesting issue that I can't resolve, maybe someone has seen it before.
The simplified example is as follows: we have a directory called "a[2-1]" that we list the files in using glob.glob(f"{path}/*")
. Glob reads the argument as a regex and crashes because 2-1
is not a valid interval. It looks like the [] are still handled as special characters, regardless of how many backslashes I put in front of them.
Any ideas?
>>> glob.glob(r"a[2-1*")
['a[2-1]']
>>> glob.glob(r"a[2-1]*")
re.error: bad character range 2-1 at position 6
>>> glob.glob(r"a[2-1\]*")
re.error: bad character range 2-1 at position 6
>>> glob.glob(r"a[2-1\\]*")
re.error: bad character range 2-1 at position 6
>>> glob.glob(r"a[2-1\\\]*")
re.error: bad character range 2-1 at position 6
The glob-doc says that the match is done with fnmatch. It tells you:
For a literal match, wrap the meta-characters in brackets. For example,
'[?]'
matches the character'?'
.
So you should use:
glob.glob('a[[]2-1[]]*')