I am trying to append a string to a file, if the string doesn\'t exit in the file. However, opening a file with a+
option doesn\'t allow me to do at once, because o
To leave the input file unchanged if needle
is on any line or to append the needle at the end of the file if it is missing:
with open("filename", "r+") as file:
for line in file:
if needle in line:
break
else: # not found, we are at the eof
file.write(needle) # append missing data
I've tested it and it works on both Python 2 (stdio-based I/O) and Python 3 (POSIX read/write-based I/O).
The code uses obscure else
after a loop Python syntax. See Why does python use 'else' after for and while loops?