Unix filenames in Python?

How does Unix filename wildcards from Python work ?

This directory contains only subdirectories, each of which has (among others) one file whose name ends with a known line, for example . The first part of the file name always changes, so I need to go to the file using this template. _ext

I wanted to do this:

directory = "."
listofSubDirs = [x[0] for x in os.walk(directory)]
listofSubDirs = listofSubDirs[1:] #removing "."

for subDirectory in listofSubDirs:
    fileNameToPickle = subDirectory + "/*_ext" #only one such file exists
    fileToPickle = pickle.load(open(fileNameToPickle, "rb"))
    ... do stuff ...

But pattern matching does not occur. How does it work under Python?

+5
source share
1 answer

Python. fnmatch glob . fnmatch , glob fnmatch , os.listdir(), .

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"))

, glob(), ; */ :

import glob
import os

for filename in glob.glob(os.path.join(directory, '*/*_ext')):
    # loops over matching filenames in all subdirectories of `directory`.
+9

All Articles