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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With