Jan-25-2023, 07:38 PM
As mention pathlib is a better choice,for search a word i would prefer regex rather than glob.
pathlib has own glob Path.glob.
To give a example with regex as mention,this search for word
A stricter search can eg add
pathlib has own glob Path.glob.
To give a example with regex as mention,this search for word
life
in filename.from pathlib import Path import re my_dir = r'C:\code\a_folder' pattern = re.compile(r'life') for file in Path(my_dir).iterdir(): if file.is_file: if re.search(pattern, file.stem): print(file)
Output:C:\code\a_folder\life.py
C:\code\a_folder\life.txt
C:\code\a_folder\life_Kopi.py
C:\code\a_folder\meaninglife.py
Also see that pathlih always give full path back,then do not need too use join()
to get full path.A stricter search can eg add
\b
to do a whole words only search.pattern = re.compile(r'\blife\b')
Output:C:\code\a_folder\life.py
C:\code\a_folder\life.txt