File existence check with partial filename

Gary Herron gherron at islandtraining.com
Mon Mar 15 00:29:26 EDT 2010


Alf P. Steinbach wrote:
> * Sang-Ho Yun:
>> I learned that I can check the existence of a file using
>> os.path.isfile("filename").
>>
>> What if I need to check if there is a file that contains "HV" in the
>> filename?  What should I do?
>
> <code>
>     from __future__ import print_function
>     import os
>
>     for filename in os.listdir( "." ):
>         if "HV" in filename.upper():
>             print( filename )
> </code>
>
>
> Cheers & hth.,
>
> - Alf

Or learn the glob module.  It allows you to ask for a list of files 
matching a pattern that can include wildcard characters  -- probably 
"*HV*" for your case.

Gary Herron




More information about the Python-list mailing list