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

隐身守侯 提交于 2020-06-23 04:29:30

问题


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?


回答1:


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



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/36040884/search-for-a-file-containing-substring-in-a-folder-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!