Search code examples
pythonif-statementreadlines

Comparing all Contents of a list to all lines within a text File


Below I have a list identifiers where values are appended within for loop logic not shown, this part is fine as it's quite basic.

The next part is where I am quite confused as to what I am doing wrong, so I open a local text file and readLines here, I use a for loop to iterate through those lines. If any of the lines in the textfile match any of the lines in the identifiers list then I do not want to send an email (email function is fine). If the ID isn't in the textFile I want to write this id from identifiers list to the text file, the way it is working at the minute it does not seem to do anything.

identifiers = []
....
identifiers.append(rowList[0])
....
fo = open('localDirectory/textFile.txt', 'r+')
content = fo.read().splitlines()
for id in content:
    if any(i in id for i in identifiers):
        print("No email to send")
    else:
        fo.write(identifiers[i]+'\n') **Write new ID to indentifiers text file**
        #Send Email

Solution

  • Since you have multiple lines in identifiers that you might want to add, a straight if/else doesn't work. So you need to add a flag to see if you added lines or not, which you test for later to see if you need to send an email.

    with open('textfile.txt', "r+") as f:
        content = f.read().splitlines()
    
        id_added = False
        for i in identifiers:
            if i not in content:
                f.write(i + '\n')
                id_added = True
    
            if id_added:
                # Send email
            else:
                print("no email to send")