#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    5
    Rep Power
    0

    Python: line replacement


    How to replace line # 10 in a file, append a line at the end of the file ?
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    5
    Rep Power
    0
    I found the solution and tested this successfully on local system but when i used fabric module to deploy in remote system, it modify the local hosts file and not remote. where i am wrong ? no errors reported.

    [root@lb1oraoemc1p hp]# cat fabfile.py

    #!/usr/bin/python

    from fabric.api import cd,env,put,run

    import fileinput,sys

    env.hosts=['root@xyz'] # remote hostname xyz

    f = open('/etc/default/xymon-client')

    m = f.read().replace('XYMONSERVERS=""','XYMONSERVERS=aaa.xyz.com')

    print m

    f.close()

    f = open('/etc/default/xymon-client','w')

    f.write(m)

    f.close()

    with open("/etc/default/xymon-client","a") as myfile:

    myfile.write("CLIENTHOSTNAME=bbb.xyz.com")



    run('service xymon start')
  4. #3
  5. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,966
    Rep Power
    481
    I'd use ed . The script is

    $ ed file_to_change
    10s/.*/replacement text for line 10/
    $a
    text appended to file
    more appended text
    .
    wq
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo