问题
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