Python write line to beginning of file

How can I write a line to beginning of a file?
Who is Participating?
The only way is to write the modified content again. The easy but slightly dangerous way to rewrite the same file with the modified content. Try:
fname = 'myfile.txt'

# Open the file for reading and read all lines into memory.
f = open(fname)
content = f.readlines()

# Modify the content arbitrarily.  Here the new first line is inserted
# as the first line.
content.insert(0, 'inserted new first line\n')

# Join the lines from the list and write the resulting string 
# to the same file now opened for writing.
f = open(fname, 'w')

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.