![](/img/trans.png)
[英]check if an element from a list exists in a strings of a txt file (not working) Python
[英]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.