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
CodePudding user response:
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")
CodePudding user response:
You dont need touse for loop in if comparison, since you have been searching if a string from identifiers contained in line from file. Here is right comparison
for id in content:
if id not in identifiers:
print("No email to send")
else:
fo.write(identifiers[i] '\n') **Write new ID to indentifiers text file**
#Send Email
CodePudding user response:
You don't need to loop over your content, as you already do that in the list comprehension. Also, consider using with open(), so you automatically close your file.
identifiers = ['patternA']
with open('textfile.txt') as f:
content = f.read().splitlines()
if any(i in identifiers for i in content):
print("Present")
else:
print("Not Present")