2016-03-16 54 views
0

假设路径是“c:\ users \ test”,文件夹“test”包含许多文件。我想在测试文件夹中搜索一个文件,文件名称中包含一个单词“postfix”,它在python脚本中。有人可以帮我吗?在文件夹中搜索包含子字符串的文件,python?

+0

显示您编写的代码。查找os.walk –

回答

1

通过列出文件夹内的所有文件:

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

,比如果要求每位子里面的文件字符串:

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

glob module内置到Python是准确制定了本。

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) 

应该打印出所有包含“postfix”的文件*是与任何匹配的通配符。因此,这种模式将匹配test_postfix.csv以及mypostfix.txt

+0

查找给定文件夹中的文件,您应该将其调整为'glob.glob(path_to_folder +“* postfix *”)' –

+0

感谢您对M.T – Jules

0

请尝试以下

import os 

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

如果有必要去深入的目录,你可以使用以下。

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