Skip to main content

Posts

Showing posts from May, 2015

Python Script : Add text to beginning of a file

Hi,

Adding text to the end of file is staightforward, but it is not so obevious if text need to be added at the beginning of the file.

Below is what can be done:

===========================================

with open('hp.txt','r+') as f:
    old = f.read()
    f.seek(0)
    f.write('Lordooooo\n' + old)
f.close()


===========================================

Notes:

1. f.seek(0) sets the access point to beginning of the file.

2. If you need to add text, say after 5th character. then you need to change if like below:

f.seek(5)