inserting a line in a file using python
Question: I have a file which contains data like this:

    
    
    $ yum -- to install package
    admin1,group,n,0123456,/usr/bin 
    user2,group,n,0123456,/usr/bin
    group,n,0123456,/usr/bin
    ----->#i have to insert a new line here
    $cat -- to read contents of a file
    admin1,group,n,0123456,/usr/bin
    user2,group,n,0123456,/usr/bin
    group,n,0123456,/usr/bin
    

First, I have to find the the word `$ yum` in the file and insert a new line
before starting of the next word starting with `$`.

Some help with my code would be appreciated.

    
    
     with open("test.txt", "a") as myfile:
          for row in myfile:
                if re.match(r'$yum,i): 
                    myfile.append("user2,group,0123456,/usr/bin") 
    


Answer: Opening the file with `a` does not allow you to `file_object.append(...`, it
means when you write to the file content will be added to the end of the file
so `myfile.append("user2,group,0123456,/usr/bin")` is not remotely valid
syntax.

You can use `itertools.groupby` to group by section where lines start with a
`$`, then either add a line if the line starts with `$ yum` or just write the
lines as is:

    
    
    from itertools import groupby
    from tempfile import NamedTemporaryFile
    from shutil import move
    
    with open("in.txt") as f, NamedTemporaryFile("w",dir=".",delete=False) as out:
        grps = groupby(f,key=lambda x: x.startswith("$"))
        for k, v in grps:
            if k:
                val = next(v)
                out.write(val)
                if val.startswith("$ yum"):
                    out.writelines(next(grps,[[], [""]])[1])
                    out.write("I am a new line\n")
            else:
                out.writelines(v)
    move(out.name,"in.txt")
    

The `move(out.name,"in.txt")` will change the original file content so the
output will be:

    
    
    $ yum -- to install package
    admin1,group,n,0123456,/usr/bin 
    user2,group,n,0123456,/usr/bin
    group,n,0123456,/usr/bin
    I am a new line
    $cat -- to read contents of a file
    admin1,group,n,0123456,/usr/bin
    user2,group,n,0123456,/usr/bin
    group,n,0123456,/usr/bin
    

Os use an inner loop every time you find a line starting with $ yum and
breaking and writing the new line in the inner loop whenever you find the next
`$`:

    
    
    from tempfile import NamedTemporaryFile
    from shutil import move
    
    with open("in.txt") as f, NamedTemporaryFile("w",dir=".", delete=False) as out:
        for line in f:
            if line.startswith("$ yum"):
                out.write(line)
                for _line in f:
                    if _line.startswith("$"):
                        out.write("I am a new line\n")
                        out.write(_line)
                        break
                    out.write(_line)
            else:
                out.write(line)
    
    move(out.name,"in.txt")
    

