Arthur D. Howland
Arthur D. Howland

Reputation: 4557

Python 3 pandas directory search for a string in filename

Hello again StackExchange!

Attempting to print all files in a directory but this time I only want to print all of the .csv files that have the string ..."AMX_error"...csv somewhere in the filename. I have the "all .csv" working, but am missing that bit of search logic.

import glob
import pandas as pd

path = r'C:\Users\Desktop\Experiment\'

#Following command to search for string in the filename
allFiles = glob.glob(path + "/*.csv") & (search filename 'AMX_error' = true)

for filename in allFiles:
    print(filename)

#rest of code..

What is the notation to search for a string in a filename? Thanks!

Upvotes: 0

Views: 1641

Answers (1)

shawnheide
shawnheide

Reputation: 807

Unless you have a reason for filtering the files first, you can simply check that the string of interest is in the filename while you're in the for loop.

import glob
import pandas as pd

path = r'C:\Users\Desktop\Experiment'

#Following command to search for string in the filename
allFiles = glob.glob(path + "/*.csv")

for filename in allFiles:
    if 'AMX_error' in filename:
        print(filename)

Upvotes: 1

Related Questions