To answer your question, see
THIS link.
Append data to a file as a new line in Python.
Solution for this is a little tricky here. Let's start with the basic approach and then we will discuss drawbacks in it and see how to improve it.
Basic approach:
Open the file in append mode (‘a’). Write cursor points to the end of file.
Append ‘\n’ at the end of the file using
write()
function.
Append the given line to the file using
write()
function.
Close the file.
Well, this approach works fine if our file already exists and already has some data in it. But if the file doesn’t exist or file is empty, then this approach will fail because contents of the file will be like this.
……………………..
New added Line:
It first writes an empty line and then writes our line. But in this case, only appending a line was fine, we don’t need to write ‘
\n
’ before that.
So, our final approach should be like this:
Open the file in append & read mode (‘a+’). Both read & write cursor points to the end of the file.
Move read cursor to the start of the file.
Read some text from the file and check if the file is empty or not.
If the file is not empty, then append ‘
\n
’ at the end of the file using
write()
function.
Append a given line to the file using
write()
function.
Close the file.
This solution will work fine in both scenarios. Let’s use this solution to append a newline at the end of the file.
Suppose we have a file ‘
sample2.txt’ with the following contents:
Hello this is a sample file
It contains sample text
This is the end of file
Append new line to the file:
with open("sample2.txt", "a+") as <code>file_object</code>:
<pre lang="Python">
file_object.seek(0)
data = file_object.read(100)
if len(data) > 0 :
file_object.write("\n")
file_object.write("x y z")
Contents of the file ‘
sample2.txt’ now,
Hello this is a sample file
It contains sample text
This is the end of file
hello hi