How do I read and append to a text file in one pass?

multigoodverse picture multigoodverse · May 1, 2016 · Viewed 8.1k times · Source

I want to check if a string is inside a text file and then append that string if it's not there.

I know I can probably do that by creating two separate with methods, one for reading and another for appending, but is it possible to read and append inside the same with method?

The closest I came up with is this:

with open("file.txt","r+") as file:
    content=file.read()
    print("aaa" in content)
    file.seek(len(content))
    file.write("\nccccc")

My file.txt:

aaaaa
bbbbb

When I run the code for the first time, I get this:

aaaaa
bbbbb
ccccc

but if I run it again, this comes up:

aaaaa
bbbbb
ccc
ccccc

I would expect the third line to be ccccc.

Anyone can explain why the last two characters are truncated in the second run? Also, how do I read and append text to a file?

Answer

Daniel picture Daniel · May 1, 2016

Don't use seek on text-files. The length of the contents is not the length of the file in all cases. Either use binary file reading or use two separate withs:

with open("file.txt","r") as file:
    content=file.read()
print("aaa" in content)
with open("file.txt","a") as file:
    file.write("\nccccc")