Issue: Use common wildcard patterns (i.e., *.py, dat[0-9]*.csv, etc.) to match text when working under a Linux shell
Solution: The Fnmatch module provides two functions Fnmatch (), Fnmatchcase ()
The match pattern for #fnmatch () uses the same case-sensitive rules as the underlying file system (different depending on the operating system)
Match patterns for #fnmatchcase () are case-sensitive
>>> fromFnmatchImportFnmatch,fnmatchcase>>> Fnmatch ('foo.txt','. txt') False>>> Fnmatch ('foo.txt','*.txt') True>>> Fnmatch ('foo.txt','? oo.txt') True>>> Fnmatch ('Dat34.csv','dat[0-9]*') True>>> names=['Dat34.csv','Dat1.csv','Config.ini','foo.py']>>> [Name forNameinchNamesifFnmatch (Name,'Dat*.csv')]['Dat34.csv','Dat1.csv']>>>
>>> fnmatch ('foo.txt','*. TXT')#onWINDOWS uppercase match True>>> fnmatchcase (' foo.txt ', ' *. TXT ') #on Windows uppercase letter Matching
False
>>> >>> fnmatch ('foo.txt','*. TXT')#onOS X (MAC) uppercase match False
One potential use of these functions is when they handle non-file-name strings.
#example.py##Example of using Shell-wildcard style matching in list comprehensions fromFnmatchImportFnmatchcase as Matchaddresses= [ '5412 N CLARK ST', '1060 W ADDISON ST', '1039 W GRANVILLE AVE', '2122 N CLARK ST', '4802 N BROADWAY',]a= [addr forAddrinchAddressesifMatch (addr,'* ST')]Print(a) b= [addr forAddrinchAddressesifMatch (addr,'54[0-9][0-9] *clark*')]Print(b)
>>> ================================ RESTART ================================>>> [' 5412 N Clark St'1060 W ADDISON St'2122 N Clark St ' ['5412 N CLARK ST']
In fact, you want to write code that matches the file name, which should be done using the Glob module.
"Python Cookbook" "String and Text" 3. String matching using shell wildcard characters