Skip to content
Advertisement

Prepend line to beginning of a file

I can do this using a separate file, but how do I append a line to the beginning of a file?

f=open('log.txt','a')
f.seek(0) #get to the first position
f.write("text")
f.close()

This starts writing from the end of the file since the file is opened in append mode.

Advertisement

Answer

In modes 'a' or 'a+', any writing is done at the end of the file, even if at the current moment when the write() function is triggered the file’s pointer is not at the end of the file: the pointer is moved to the end of file before any writing. You can do what you want in two manners.

1st way, can be used if there are no issues to load the file into memory:

def line_prepender(filename, line):
    with open(filename, 'r+') as f:
        content = f.read()
        f.seek(0, 0)
        f.write(line.rstrip('rn') + 'n' + content)

2nd way:

def line_pre_adder(filename, line_to_prepend):
    f = fileinput.input(filename, inplace=1)
    for xline in f:
        if f.isfirstline():
            print line_to_prepend.rstrip('rn') + 'n' + xline,
        else:
            print xline,

I don’t know how this method works under the hood and if it can be employed on big big file. The argument 1 passed to input is what allows to rewrite a line in place; the following lines must be moved forwards or backwards in order that the inplace operation takes place, but I don’t know the mechanism

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement