簡體   English   中英

根據字符串列表遞歸檢查txt文件的內容

[英]Recursively check txt file contents against a list of strings

我需要篩選共享目錄/子目錄,閱讀txt文件,並檢查其中是否存在某些關鍵短語。


import os

stringcheck = ['my espresso machine', 'sick of these dolphins', 
               'unpaid intern', 'dynamite']

parent = os.path.expanduser("~/Google Drive/life/aquatic")

def simplecheck(parent):
    for dir in os.walk(parent):
        for files in dir:
            if files.endswith(".txt"):
                if any(x not in files.read() for x in stringcheck):
                    print " "*4 + files + "\n"

simplecheck(parent)

返回:

AttributeError: 'list' object has no attribute 'endswith'

os.walk產生元組:

[...]對於以目錄頂部(包括頂部本身)為根的樹中的每個目錄,它會生成一個(dirpath, dirnames, filenames)(dirpath, dirnames, filenames)

因此,您可能想寫:

for files in dir[-1]:

同樣, filename名將是此變量的更好名稱。

暫無
暫無

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

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