Appending to a file using Python API

Steven D'Aprano steve-REMOVE-THIS at cybersource.com.au
Thu Jul 8 03:10:58 EDT 2010


On Wed, 07 Jul 2010 23:55:46 -0700, lavanya wrote:

> 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()



-- 
Steven



More information about the Python-list mailing list