Python Script : Add text to beginning of a file


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.write('Lordooooo\n' + old)



1. 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: