hleggs hleggs - 4 months ago 6
Python Question

Most efficient way to write to file conditionally?

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:
continue
else:
database.write('MY STRING')


Firstly, what am I doing wrong here? Secondly, assuming this was functioning properly, would there be a more efficient way to do this? I am assuming there is.

Thanks

Answer

Using 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.