-1

I looked through all over, but could not find a good simple code that allows me to prepend a string to an existing file.

The file is this:

brave
charlie
delta
echo

I want to prepend "alpha" to the file so it'll look like this:

alpha
bravo
charlie
delta
echo

What is the best way to go about this? What I have tried so far is this:

with open('file', 'rb+') as fp:
     fp.seek(0)
     fp.write('alpha)

but this overwrites the first line

Carol Ward
  • 699
  • 4
  • 17
  • check [Prepend line to beginning of a file](https://stackoverflow.com/questions/5914627/prepend-line-to-beginning-of-a-file) – SanV Apr 04 '19 at 16:08

1 Answers1

1

If you want to prepend something you have to read from the file first.

with open('tmpFile.txt', 'rb+') as fp:
  file_text = fp.read()
  fp.seek(0)
  fp.write(b'alpha\n' + file_text)


original file contents:
brave
charlie
delta
echo

file contents after write:
alpha
brave
charlie
delta
echo
Life is complex
  • 15,374
  • 5
  • 29
  • 58