How Do I Read And Append To A Text File In One Pass?
Solution 1:
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:
withopen("file.txt","r") as file:
content=file.read()
print("aaa"in content)
withopen("file.txt","a") as file:
file.write("\nccccc")
Solution 2:
Use this:
withopen("file.txt","r+") as file:
content=file.read()
file.seek(0,2)
file.write("\nccccc")
Here we use fileObject.seek(offset[, whence])
with offset 0
& whence 2
that is seek to 0 characters from the end. And then write to the file.
OR (Alternate using SEEK_END):
import os
with open("file.txt", 'rb+') as file:
file.seek(-1, os.SEEK_END)
file.write("\nccccc\n")
Here we seek to SEEK_END
of the file(with the os package) and then write to it.
Solution 3:
Why not do this? Note, the first with
statement is used for creating the file, not for reading or appending. So this solutions uses only one with to read and append.
string="aaaaa\nbbbbb"
with open("myfile", "w") as f:
f.write(string)
with open("myfile", "r+") as f:
ifnot"ccccc"in f.read():
f.write("\nccccc")
Solution 4:
seek()
is based on bytes, and your text file may not be encoded with precisely one byte per character. Since read()
reads the whole file and leaves the pointer at the end, there's no need to seek anyway. Just remove that line from your code and it will work fine.
with open("file.txt","r+") as file:
content=file.read()
print("aaa"in content)
file.write("\nccccc")
Post a Comment for "How Do I Read And Append To A Text File In One Pass?"