[英]Commenting a pattern of line in a file
我需要注釋一組具有相似模式且具有唯一值的行。
例子
a {
1
2 one
3
}
a {
1
2 two
3
}
在上面的示例中,我需要注釋整個塊。 基於這樣的唯一值“二”。
a {
1
2 one
3
}
#a {
#1
#2 two
#3
#}
以上我能夠獲得帶有索引行的塊,但無法進行就地編輯或替換。 我正在使用 python2 代碼:
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)
我不認為你可以就地做到這一點。 您可以做的是先讀取文件,注釋其內容,然后寫入文件。 像這樣的東西
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)
假設搜索的文本將始終存在於文件中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.