Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put a string at the front of a file in python

Tags:

python

this is my code:

>>> p = open(r'/Users/ericxx/Desktop/dest.txt','r+')
>>> xx = p.read()
>>> xx =  xx[:0]+"How many roads must a man walk down\nBefore they call him a man" +xx[0:]
>>> p.writelines(xx)
>>> p.close()

the original file content looks like:

How many seas must a white dove sail Before she sleeps in the sand


the result looks like :

How many seas must a white dove sail Before she sleeps in the sand 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


expected output :

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

like image 825
ericxxcc Avatar asked Nov 30 '25 03:11

ericxxcc


1 Answers

You have to "rewind" the file between reading and writing:

p.seek(0)

The whole code will look like this (with other minor changes):

p = open('/Users/ericxx/Desktop/dest.txt','r+')
xx = p.read()
xx = "How many roads must a man walk down\nBefore they call him a man" + xx
p.seek(0)
p.write(xx)
p.close()
like image 51
Messa Avatar answered Dec 01 '25 17:12

Messa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!