ericxxcc
ericxxcc

Reputation: 21

How to put a string at the front of a file in 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

Upvotes: 3

Views: 77

Answers (2)

Torxed
Torxed

Reputation: 23490

Adding to @messas answer, while doing seek to add the data in the front it can also leave you with old data at the end of your file if you ever shortened xx at any point.

This is because p.seek(0) puts the input pointer in the file at the beginning of the file and any .write() operation will overwrite content as it goes. However a shorter content written vs content already in the file will result in som old data being left at the end, not overwritten.

To avoid this you could open and close the file twice with , 'w') as the opening parameter the second time around or store/fetch the file contents length and pad your new content. Or truncate the file to your new desired length.

To truncate the file, simply add p.flush() after you've written the data.

Also, use the with operator

with open('/Users/ericxx/Desktop/dest.txt','r+') as p:
    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.flush()

I'm on my phone so apologies if the explanation is some what short and blunt and lacking code. Can update more tomorrow.

Upvotes: 1

Messa
Messa

Reputation: 25191

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()

Upvotes: 5

Related Questions