Appending to a file using Python API

L

lavanya

Hello all,

How do you append to a file using Python os::file APIs. So that it
appends to the content of the file. Not adding the content to the new
line. But just appends next to the exiting content of the file.

Example : current content of file
A B C
if we append D to it, it should be
A B C D

Not like:
A B C
D

regards,
lavanya
 
S

Steven D'Aprano

Hello all,

How do you append to a file using Python os::file APIs. So that it
appends to the content of the file. Not adding the content to the new
line. But just appends next to the exiting content of the file.

Example : current content of file
A B C
if we append D to it, it should be
A B C D

Not like:
A B C
D

f = open("myfile.txt", "a")
f.write("D")

will append to the end of myfile.txt, regardless of what is already in
myfile.txt. If it ends with a newline:

"A B C\n"

then you will end up with:

"A B C\nD"

If there is no newline, you will end up with:

"A B CD"


If you need anything more complicated than that, the easiest solution is
something like this:


# read the entire file
# modify the last line in memory
# write the lines back to the file
f = open("myfile.txt", "r")
lines = f.readlines()
f.close()
if not lines:
# file exists but is empty
lines.append('')
last_line = lines[-1]
last_line = last_line.rstrip() # remove all trailing whitespace
if last_line:
last_line += " D\n"
else:
last_line = "D\n"
lines[-1] = last_line
f = open("myfile.txt", "w")
f.writelines(lines)
f.close()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
SterlingLa
Top