簡體   English   中英

在python中搜索包含子字符串的文件?

[英]search for a file containing substring in a folder, python?

假設路徑為“c:\\ users \\ test”,文件夾“test”包含許多文件。 我想在測試文件夾中搜索一個文件,文件名在python腳本中包含一個單詞“postfix”。 任何人都可以幫助我嗎?

列出文件夾中的所有文件:

    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

內置於python的glob模塊正是為此而制作的。

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

請嘗試以下方法

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM