I would like to write a string to a file only if it's not presently in the file.
My first thought was to do something like this, however it's not writing anything to the file.
with open("FILE PATH", "a+") as database:
for lines in database.read():
if 'MY STRING' in lines:
database.read() will read your text file and return a single string containing the entire file. Looping over this string will return each character within that string individually, so you won't find
'MY STRING' in it. Simply look for
'MY STRING' within the file as a whole like so:
with open("FILE PATH", "a+") as database: if 'MY STRING' not in database.read(): database.write('MY STRING')
You don't need the first
if statement seeing as it's only a
continue, like this you only have one
if, making it a little more efficient.