0

I have 2 lists. A list of files, and a list of sentences. I am trying to loop thru all of the files, for all of the sentences. If any of the sentences does NOT exist in any of the files, I want to know what file is not complete.

My current code, when it runs. Its only showing 1 match, the first line. No matter if I add or remove the text its looking for (see examples below).

Thanks in advance for any help.

Example Current Code

# =====
# IMPORTS
import glob
from os import listdir
from os.path import isfile, join
# =====

# =====
# VARIABLES
# Path of the configs
cPath = r"\confgFiles"
# List for the files in folder
cFiles = [f for f in listdir(cPath) if isfile(join(cPath, f))]
# Strings to look for
cFind = ["remark ------------ Random Item ----------",
"remark ------Random Item 05-01-2020 ------",
"object-group network 17895452",
 "host 65498616",
 "host 9498419156",
 "host 619619615",
 "host 9646465456",
 "host 946464986",
 "host 65465465456",
 "host 746864564",
 "host 456456456",
 "host 456456456",
 "host 456456456",
 "host 456456456",
 "host 456456456",
 "host 456456456",
 "host 456456456",
 "host 456456456"
]
# =====

for file in cFiles:
    print("Starting: " + file)
    with open(cPath + "\\" + file) as f:
        for iFind in cFind:
            if iFind in f.read():
                print("true")
            else:
                print("false")

Example File:

remark ------------ Random Item ----------
remark ------Random Item 05-01-2020 ------
object-group network 17895452
 host 65498616
 host 9498419156
 host 619619615
 host 9646465456
 host 946464986
 host 65465465456
 host 746864564
 host 456456456
 host 456456456
 host 456456456
 host 456456456
 host 456456456
 host 456456456
 host 456456456
 host 456456456

Output:

Starting: Config1.txt
true
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
dwb
  • 475
  • 6
  • 31
  • The underlying problem is that you have your `read()` call inside the `for` loop (because it's part of your `if` condition) - please see the linked duplicate. But it comes across to me like you might be intending to compare each line of `cFind` to *the corresponding line* of the file, rather than searching for it in the entire file contents. That's a much different question. – Karl Knechtel May 11 '20 at 20:33
  • You can do this much faster by turning `cFind` into a `set`. Read each file once and turn its content into a set (`with open(cPath + "\\" + file) as f: cGot = set(line.strip() for lline in f)`. Now, you can just `cFind - cGot` to subtract sets, and the result is anything in cFind that wasnt' in the file. – tdelaney May 11 '20 at 20:39

0 Answers0