0

Does anyone know of a easy way to enter a file at the beginning and add to it on the first line?

I tried doing the following:

f.seek(0)

f.write("....")

f.close() 

The only problem is that it doesn't add a new first line with what I want, rather replaces it.

Does anyone know any way, either while writing the file to add the last line on top or after closing it and reopening to add a line to the first line without overwriting or replacing anything?

1478963
  • 1,198
  • 4
  • 11
  • 25
learner
  • 137
  • 1
  • 1
  • 6

1 Answers1

2

Although ugly it works:

# read the current contents of the file
f = open('filename')
text = f.read()
f.close()
# open the file again for writing
f = open('filename', 'w')
f.write("This is the new first line\n")
# write the original contents
f.write(text)
f.close()

Also the word you are looking for is pre-pending. Also I don't think this will work if you can't load the file to memory (if its too big).

If it is too large you can write the line, then write line by line.

Alternate (havent tested)

you can use fileinput

>>> import fileinput
>>> for linenum,line in enumerate( fileinput.FileInput("file",inplace=1) ):
...   if linenum==0 :
...     print "new line"
...     print line.rstrip()
...   else:
...     print line.rstrip()
...

From: How to insert a new line before the first line in a file using python?

Community
  • 1
  • 1
1478963
  • 1,198
  • 4
  • 11
  • 25