Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepend line to beginning of a file

Tags:

python

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.

like image 574
Illusionist Avatar asked May 06 '11 16:05

Illusionist


People also ask

How do you append a line at the beginning of a file in Unix?

If you want to add a line at the beginning of a file, you need to add \n at the end of the string in the best solution above. The best solution will add the string, but with the string, it will not add a line at the end of a file. On Mac OS, was getting error with "undefined label".

How do you append the output to the beginning of a text file?

The operator '>' writes output to a new file, or to an existing file; in which case it wipes off everything which is previously present in the file. The operator '>>' on the other hand appends output at the end of an existing file. However, there is no dedicated operator to write new text to the beginning of a file.

How do you prepend text in Linux?

1s;^;to be prepended; substitutes the beginning of the first line by the given replacement string, using ; as a command delimiter.


2 Answers

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('\r\n') + '\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('\r\n') + '\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

like image 135
eyquem Avatar answered Sep 23 '22 23:09

eyquem


In all filesystems that I am familiar with, you can't do this in-place. You have to use an auxiliary file (which you can then rename to take the name of the original file).

like image 38
NPE Avatar answered Sep 23 '22 23:09

NPE