Home > database >  searching specific string in list
searching specific string in list

Time:01-29

How to search for every string in a list that starts with a specific string like:

path = (r"C:\Users\Example\Desktop")
desktop = os.listdir(path)
print(desktop)
#['faf.docx', 'faf.txt', 'faad.txt', 'gas.docx']

So my question is: how do i filter from every file that starts with "fa"?

CodePudding user response:

For this specific cases, involving filenames in one directory, you can use globbing:

import glob
import os

path = (r"C:\Users\Example\Desktop")
pattern = os.path.join(path, 'fa*')
files = glob.glob(pattern)

CodePudding user response:

This code filters all items out that start with "fa" and stores them in a separate list

filtered = [item for item in path if item.startswith("fa")]

CodePudding user response:

All strings have a .startswith() method!

results = []
for value in os.listdir(path):
    if value.startswith("fa"):
        results.append(value)
  •  Tags:  
  • Related