So, I have textfile with multiple lines:
orange
melon
applez
more fruits
abcdefg
And I have a list of strings that I want to check:
names = ["apple", "banana"]
Now I want to go through all the lines in the file, and I want to insert the missing strings from the names list, if they are not present. If they are present, then they should not be inserted.
Generally this should not be to difficult but taking care of all the newlines and such is pretty finicky. This is my attempt:
if not os.path.isfile(fpath):
raise FileNotFoundError('Could not load username file', fpath)
with open(fpath, 'r+') as f:
lines = [line.rstrip('\n') for line in f]
if not "banana" in lines:
lines.insert(0, 'banana')
if not "apple" in lines:
lines.insert(0, 'apple')
f.writelines(lines)
print("done")
The problem is, my values are not inserted in new lines but are appended. Also I feel like my solution is generally a bit clunky. Is there a better way to do this that automatically inserts the missing strings and takes care of all the newlines and such?