0

I want to write a file and then modify it by inserting some other content to the beginning and end of the file.

My code:

f = open('Blowing in the wind.txt', 'w+')
f.seek(0)
f.truncate()
f.write('''
How many roads must a man walk down

Before they call him a man

How many seas must a white dove sail

Before she sleeps in the sand
''')
content= f.read()
f.seek(0)
f.write('Blowing in the wind\n' + 'Bob\n'+content)
f.seek(0,2)
f.write('\n1962 by Warner Bros.Inc.')
f.seek(0,0)
txt= f.read()
print(txt)

Result:

Blowing in the wind
Bob
n walk down

Before they call him a man

How many seas must a white dove sail

Before she sleeps in the sand

1962 by Warner Bros.Inc.

How to prevent the added content from overwriting the first line in original text?

martineau
  • 119,623
  • 25
  • 170
  • 301
Psyduck
  • 637
  • 3
  • 10
  • 22

1 Answers1

0

You may read the file content data = f.read()

new_data = "start" + data + "end"

You may open file with 'w' mode and do

f.write(new_data)

rkatkam
  • 2,634
  • 3
  • 18
  • 29
  • Hi, I read the help file and I thought w+ could do all w can do? So I am assuming it's ok to use w+ instead of w? – Psyduck Jul 28 '17 at 19:07
  • And also when I tried to use "a+" to open the file, even I move the pointer to the beginning with seek(0), the additional text was still appended to the end of the original file, why is this? – Psyduck Jul 28 '17 at 19:08
  • You need to to have two file instances, one with 'r' mode, and next with 'w+' mode – rkatkam Jul 28 '17 at 19:10
  • @Noob: most file systems do not allow insertion to an existing file anywhere except at the end, regardless of the programming language. – cdarke Jul 28 '17 at 19:14
  • @rkatkam The code you provided above is same with those part in my code content= f.read() f.seek(0) f.write('Blowing in the wind\n' + 'Bob\n'+content) Do you mean I should open another new file and use f.write(new_data) to write into the new file? – Psyduck Jul 28 '17 at 19:48