Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

File existence check with partial filename

5 views
Skip to first unread message

Sang-Ho Yun

unread,
Mar 15, 2010, 12:57:39 AM3/15/10
to
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?

Thank you,
Sang-Ho

Alf P. Steinbach

unread,
Mar 15, 2010, 12:24:46 AM3/15/10
to
* Sang-Ho Yun:

<code>
from __future__ import print_function
import os

for filename in os.listdir( "." ):
if "HV" in filename.upper():
print( filename )
</code>


Cheers & hth.,

- Alf

Gary Herron

unread,
Mar 15, 2010, 12:29:26 AM3/15/10
to pytho...@python.org

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

MRAB

unread,
Mar 15, 2010, 11:44:43 AM3/15/10
to pytho...@python.org
Lan Qing wrote:
> Or use the regular module:
>
> import re

> import os
>
> for filename in os.listdir('.'):
> if re.match("*HV*", filename):
> # do something with the file
>
The regular expression should be ".*HV.*", although:

re.search("HV", filename)

would be better and:

"HV" in filename.upper()

would be even better, as Alf posted.

> --
> http://mail.python.org/mailman/listinfo/python-list
>
>

Steven Howe

unread,
Mar 15, 2010, 1:20:10 PM3/15/10
to pytho...@python.org
What wrong with glob?
-----------------------
Help on module glob:

NAME
glob - Filename globbing utility.

FILE
/usr/lib64/python2.6/glob.py

FUNCTIONS
glob(pathname)
Return a list of paths matching a pathname pattern.

The pattern may contain simple shell-style wildcards a la fnmatch.

iglob(pathname)
Return an iterator which yields the paths matching a pathname
pattern.

The pattern may contain simple shell-style wildcards a la fnmatch.

DATA
__all__ = ['glob', 'iglob']

-------------------
solution:

import glob

for afile in glob.iglob( "/home/buddy/*.HV" ):
print afile


sph


On 03/15/2010 08:44 AM, MRAB wrote:
> Lan Qing wrote:
>> Or use the regular module:
>>
>> import re

>> import os
>>
>> for filename in os.listdir('.'):

>> if re.match("*HV*", filename):
>> # do something with the file
>>
> The regular expression should be ".*HV.*", although:
>
> re.search("HV", filename)
>
> would be better and:
>
> "HV" in filename.upper()
>
> would be even better, as Alf posted.
>
>> On Mon, Mar 15, 2010 at 12:24 PM, Alf P. Steinbach <al...@start.no
>> <mailto:al...@start.no>> wrote:
>>

>> -- http://mail.python.org/mailman/listinfo/python-list
>>
>>
>

0 new messages