3

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

Ramesh Raithatha
  • 544
  • 1
  • 7
  • 18
  • split over carriage return (\n) and loop through all lines incrementing a var. every 20 lines, insert whatever string you need. you could also have a regex with 20 carriage return – Youn Elan Mar 06 '13 at 03:32

3 Answers3

5

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)
Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52
3
$ head -n 20 input.txt > output.txt
$ echo "---" >> output.txt
$ tail -n 30 input.txt >> output.txt
Roozbeh Zabihollahi
  • 7,207
  • 45
  • 39
0

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.

Community
  • 1
  • 1
Aneesh Dogra
  • 740
  • 5
  • 30