Python write line to beginning of file

How can I write a line to beginning of a file?
DennieAsked:
Who is Participating?
 
peprCommented:
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:

a.py
fname = 'myfile.txt'

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

# 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')
f.write(''.join(content))
f.close()

Open in new window

0
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.