Python Forum

Full Version: search file by regex
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,

Search specific string name file in folder. How to config regular match.

folder include files as below:
Check_noise#3_P020_20211220_094542_CAMEMSNIOSAI31_2D.csv
Check_noise#3_P020_20211220_100122_CAMEMSNIOSAI31_2D.csv
check noise_P020_20220504_085928_CAMEMSNIOSAI11_2D.csv
check noise_P020_20220504_131424_CAMEMSNIOSAI11_2D.csv
te_noise_P020_20220713_170832_CAMEMSNIOSAI21_2D.csv
noise_P020_20220802_153723_CAMEMSNIOSAI21_2D.csv
noise_P020_20220803_085104_CAMEMSNIOSAI31_2D.csv
noise_P020_20221226_153635_CAMEMSNIOSAI11_2D.csv
gyl_P020_20230214_102731_CAMEMSNIOSAI41_2D.csv
gyl_Noise_P020_20230214_144514_CAMEMSNIOSAI41_2D.csv
gyl_P020_20230215_100622_CAMEMSNIOSAI21_2D.csv
noise_P020_20230213_213718_CAMEMSNIOSAI31_2D.csv
noise_P020_20230217_205552_CAMEMSNIOSAI21_2D.csv

I will take out include "gyl',"gyl noise","noise" string file .
////////////////////////////////////////////////////////////////////////////
noise_P020_20220802_153723_CAMEMSNIOSAI21_2D.csv
noise_P020_20220803_085104_CAMEMSNIOSAI31_2D.csv
noise_P020_20221226_153635_CAMEMSNIOSAI11_2D.csv
gyl_P020_20230214_102731_CAMEMSNIOSAI41_2D.csv
gyl_Noise_P020_20230214_144514_CAMEMSNIOSAI41_2D.csv
gyl_P020_20230215_100622_CAMEMSNIOSAI21_2D.csv
noise_P020_20230213_213718_CAMEMSNIOSAI31_2D.csv
noise_P020_20230217_205552_CAMEMSNIOSAI21_2D.csv
///////////////////////////////////////////////////////////////////////////

can you share me a good way to do that,thanks!



import re
from pathlib import Path
basepath = Path(r'C:\Eng\CSV')
pattern = '.*(gyl|noise)'
matching_files = []

for _path in [p for p in basepath.rglob('*.csv')]:
    if re.match(pattern, _path.name):
        matching_files.append(_path)
        print(_path.name)
You don't want .* at the start of your pattern. "noise|gyl" should work fine.