Sahil
Sahil

Reputation: 31

search for a file containing substring in a folder, python?

Suppose the path is "c:\users\test" , the folder "test" contains many files. i want to search for a file in test folder ,file name containing a word "postfix" in it in python script. Can anybody help me with it?

Upvotes: 2

Views: 9533

Answers (3)

Mayur Buragohain
Mayur Buragohain

Reputation: 1615

Try the following

import os

itemList =  os.listdir("c:\users\test")
print [item for item in itemList if "postfix" in item]

If there is an need to go deeper into the directories,you could use the following.

    import os

    filterList = []
    def SearchDirectory(arg, dirname, filename):
        for item in filename:
            if not os.path.isdir(dirname+os.sep+item) and "posix" in item:
                filterList.append(item)

    searchPath = "c:\users\test"
    os.path.walk(searchPath, SearchDirectory, None)

    print filterList

Upvotes: 0

Jules
Jules

Reputation: 973

The glob module builtin to python is made exactly for this.

import glob
path_to_folder = "/path/to/my/directory/"
matching_files = glob.glob(path_to_folder+"*postfix*")
for matching_file in matching_files:
    print(matching_file)

should print out all of the files that contain "postfix" the * are wildcard characters matching anything. Therefore this pattern would match test_postfix.csv as well as mypostfix.txt

Upvotes: 5

armatita
armatita

Reputation: 13485

By listing all files inside folder:

    from os import listdir
    from os.path import isfile, join
    onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

, and than asking each if substring in inside file string:

    for i in onlyfiles:
         if "postfix" in i:
              # do something

Upvotes: 5

Related Questions