Unix filename wildcards in Python?

后端 未结 1 1442
南方客
南方客 2021-01-05 11:32

How do Unix filename wildcards work from Python?

A given directory contains only subdirectories, in each of which there is (among o

相关标签:
1条回答
  • 2021-01-05 12:09

    Shell wildcard patterns don't work in Python. Use the fnmatch or glob modules to interpret the wildcards instead. fnmatch interprets wildcards and lets you match strings against them, glob uses fnmatch internally, together with os.listdir() to give you a list of matching filenames.

    In this case, I'd use fnmatch.filter():

    import os
    import fnmatch
    
    for dirpath, dirnames, files in os.walk(directory):
        for filename in fnmatch.filter(files, '*_ext'):
            fileNameToPickle = os.path.join(dirpath, filename)
            fileToPickle = pickle.load(open(fileNameToPickle, "rb"))
    

    If your structure contains only one level of subdirectories, you could also use a glob() pattern that expresses that; the */ in the path of expression is expanded to match all subdirectories:

    import glob
    import os
    
    for filename in glob.glob(os.path.join(directory, '*/*_ext')):
        # loops over matching filenames in all subdirectories of `directory`.
    
    0 讨论(0)
提交回复
热议问题