Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert string at the beginning of each line

How can i insert a string at the beginning of each line in a text file, i have the following code:

f = open('./ampo.txt', 'r+')
with open('./ampo.txt') as infile:
    for line in infile:
        f.insert(0, 'EDF ')
f.close

i get the following error:

"'file' object has no attribute 'insert'"

Please note that im a complete programming n00b.

like image 757
philberndt Avatar asked Oct 03 '11 09:10

philberndt


People also ask

How do you add a string at the beginning of each line in Linux?

The sed command can be used to add any character of your choosing to the beginning of each line. This is the same whether you are adding a character to each line of a text file or standard input.

How do I add text to the beginning of a file in bash?

To add the text at the beginning of the existing first line, use the -n argument of echo. Note that although Bash or many other shells do not have a limit on the size of a variable, however, the size may be limited based on the environment and system configuration.


1 Answers

Python comes with batteries included:

import fileinput
import sys

for line in fileinput.input(['./ampo.txt'], inplace=True):
    sys.stdout.write('EDF {l}'.format(l=line))

Unlike the solutions already posted, this also preserves file permissions.

like image 51
unutbu Avatar answered Oct 11 '22 05:10

unutbu