pythonfilecommentspython-2.xinplace-editing

Commenting a pattern of line in a file


I need to comment a set of line which has similar pattern with a unique value on it.

example

a {
1
2 one
3
}


a {
1
2 two
3
}

In the above example I need to comment the entire block. base on the unique value "two" like this.

a {
1
2 one
3
}

#a {
#1
#2 two
#3
#}

The above I'm able to get the block with index line but unable to do a inplace edit or replace. I'm using python2 code:

line = open('file').readlines()
index = line.index('two\n')
abline = int(index)-2
beline = int(abline)+5
for linei in range(abline,beline+1):
    nline = '%s%s' % ("##",line[linei].strip())
    print(nline)

Solution

  • I don't think you can do it inplace. what you can do is read the file first, comment its content and then write into the file. something like this

    lines = open('file').readlines()
    
    index = -1
    
    for ind,line in enumerate(lines):
        if 'two' in line:
            index = ind 
    
    commented_lines = ''
    for ind,line in enumerate(lines):
        if ind >= index-2 and ind <=index+2:
            commented_lines += '#%s' %line
        else:
            commented_lines += line
    
    
    with open('file', 'w') as f:
        f.write(commented_lines)
    

    assuming the searched text will always be present in the file.