Search code examples
regexpython-3.xfilenamesglob

Python3: File Globbing by Whole Strings


I understand file globbing in Python3 very well. However, the official Python3 documentation did not have anything on what I want to ask. I have a folder with many Xaiml files (XML databases for Betabots). I am grouping certain files together. For instance, I used

glob.glob('./temp/xaiml2/[IiJjKkLlPpQqRr]*.[Xx][Aa][Ii][Mm][Ll]')

so that I could later put these files into one file. Here is the challenge, I want to group files together that start with S, s, T, t, U, u, V, v, and dict8. Yes, files starting with a full string that may have other characters after it. I have tried doing code like [SsTtUuVv'dict8'], but the glob command does not like that ('SyntaxError: invalid syntax'). Is this possible, and if so, how? Is glob.glob even the right command for this use?


Solution

  • You will need to use os.listdir() to get the directory contents, and then re.match() to match the filename contents.

    [f for f in os.listdir(somedir) if re.match(r'([s-v]|dict8).*\.xaiml', f, re.I)]