Skip to content

Instantly share code, notes, and snippets.

@bkamapantula
Created October 31, 2011 02:29
Show Gist options
  • Save bkamapantula/1326779 to your computer and use it in GitHub Desktop.
Save bkamapantula/1326779 to your computer and use it in GitHub Desktop.
Append text in existing file in Python - Day 11
from numpy import*
values = []
#after operations using values array, we write the output to a text file
with open("appendLines.txt", "a") as newf:
newf.write('\n')
newf.write(str(len(values)))
newf.write('\t')
newf.write(str(sum(values)))
newf.write('\t')
newf.write(str(average(values)))
#newf.write('\n')
newf.close
@jacobhalls
Copy link

When you open with "a" mode , the write position will always be at the end of the file (an append). There are other permutations of the mode argument for updating (+), truncating (w) and binary (b) mode but starting with just "a" is your best. If you want to seek through the file to find the place where you should insert the line, use 'r+'.

The following code append a text in the existing file:

with open("index.txt", "a") as myfile:
    myfile.write("text appended")

source: How to append a file in Python

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment