Python Forum
python print all files which contain specific word in it
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python print all files which contain specific word in it
#4
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 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
Reply


Messages In This Thread
RE: python print all files which contain specific word in it - by snippsat - Jan-25-2023, 07:38 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Help replacing word in Mutiple files. (SOLVED) mm309d 0 888 Mar-21-2023, 03:43 AM
Last Post: mm309d
  python move specific files from source to destination including duplicates mg24 3 1,156 Jan-21-2023, 04:21 AM
Last Post: deanhystad
  Failing to print sorted files tester_V 4 1,352 Nov-12-2022, 06:49 PM
Last Post: tester_V
  delete all files which contains word sql_Table1 mg24 2 918 Sep-15-2022, 10:05 PM
Last Post: mg24
  [GoogleTrans] How can i print my translation word ?... JamieVanCadsand 7 11,834 Aug-29-2021, 12:01 PM
Last Post: Melcu54
Question Problem: Check if a list contains a word and then continue with the next word Mangono 2 2,576 Aug-12-2021, 04:25 PM
Last Post: palladium
  Moving specific files then unzipping/decompressing christophereccles 2 2,408 Apr-24-2021, 04:25 AM
Last Post: ndc85430
  How to make a telegram bot respond to the specific word in a sentence? Metodolog 2 6,438 Dec-22-2020, 07:30 AM
Last Post: martabassof
  Searching for specific word in text files. JellyCreeper6 1 1,775 Nov-03-2020, 01:52 PM
Last Post: DeaD_EyE
  Find specific subdir, open files and find specific lines that are missing from a file tester_V 8 3,740 Aug-25-2020, 01:52 AM
Last Post: tester_V

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020