python - Filtering for multiple strings on f.read -
ive been playing various ways filter multiple strings on f.read()
. cant seem find 1 works id expect to, apart multiple separate loops refuse believe there isn't more elegant solution.
i trying akin to:
if 'string' or 'string2' or 'string3' in f.read():
i have tried few variations such as:
if ('string1', 'string2','string3') in f.read(): if f.read() ('string1', 'string2','string3'):
of course i've not found way working in manner expect, , google , docs failing to, enlighten me?
after kasramvd's enlightenment below shows both elegance , function. take note of finale line specifically.
check_list = ['string1', 'string2', 'string3'] filename in files: f = open(root + filename) fi = f.read() if any(i in fi in check_list):
you close in fist code need use or
between conditions not objects, can change following :
with open('file_name') f: fi = f.read() if 'string' in fi or 'string2' in fi or 'string3' in fi:
but instead of can use built-in function any
:
with open('file_name') f: fi = f.read() if any(i in fi in word_set)
and if dealing huge file instead of loading whole of file content in memory can check existence of strings in each line function :
def my_func(word_set): open('file_name') f: line in f: if any(i in line in word_set): return true return false
Comments
Post a Comment