hi All,

Looking for the python code which adds the lines to existing file at the beginning of the
file. Tried using the seek method but not able to succeed.
Can any one please help on this ?

The best solution is to read the whole file and rewrite it

def prepend(data, filename):
    file_content = open(filename).read()
    with open(filename, "w") as fout:
        fout.write(data)
        fout.write(file_content)

if __name__ == "__main__":
    prepend("hello world\n", "myfile.txt")

Note: there is a risk here: if you pass invalid data, the fout.write(data) may fail and the function will erase your file. So you could add some more code to restore the file in the case where fout.write(data) raises an exception.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.