File existence check with partial filename

A

Alf P. Steinbach

* 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
 
G

Gary Herron

Alf said:
* 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

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
 
S

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?

Thank you,
Sang-Ho
 
M

MRAB

Lan said:
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.
 
S

Steven Howe

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top