2016-03-16 55 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 
相關問題