Harrison
Harrison

Reputation: 5386

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

Upvotes: 1

Views: 73

Answers (1)

Girrafish
Girrafish

Reputation: 2482

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')

Upvotes: 1

Related Questions