Ramesh Raithatha
Ramesh Raithatha

Reputation: 544

How to add a string to a specific line

I have a file which contains 50 lines. How can i add a string "-----" to a specific line say line 20 using python/linux ?

Upvotes: 3

Views: 4600

Answers (3)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29111

Have you tried something like this?:

exp = 20 # the line where text need to be added or exp that calculates it for ex %2

with open(filename, 'r') as f:
    lines = f.readlines()

with open(filename, 'w') as f:
    for i,line in enumerate(lines):
        if i == exp:
            f.write('------')
        f.write(line)

If you need to edit diff number of lines you can update code above this way:

def update_file(filename, ln):
    with open(filename, 'r') as f:
        lines = f.readlines()

    with open(filename, 'w') as f:
        for idx,line in enumerate(lines):
            (idx in ln and f.write('------'))
            f.write(line)

Upvotes: 5

Aneesh Dogra
Aneesh Dogra

Reputation: 740

If the file to read is big, and you don't want to read the whole file in memory at once:

from tempfile import mkstemp
from shutil import move
from os import remove, close

line_number = 20

file_path = "myfile.txt"

fh_r = open(file_path)
fh, abs_path = mkstemp()
fh_w = open(abs_path, 'w')

for i, line in enumerate(fh_r):
    if i == line_number - 1:
        fh_w.write('-----' + line)
    else:
        fh_w.write(line)

fh_r.close()
close(fh)
fh_w.close()

remove(file_path)
move(abs_path, file_path)

Note: I used Alok's answer here as a reference.

Upvotes: 0

Roozbeh Zabihollahi
Roozbeh Zabihollahi

Reputation: 7347

$ head -n 20 input.txt > output.txt
$ echo "---" >> output.txt
$ tail -n 30 input.txt >> output.txt

Upvotes: 3

Related Questions