在文本文件中,我想搜索包含特定文本的行,并且在下一行我想用 #(注释掉)替换行的开头:
示例 - 之前:
#test search 123
text to be commented out
#test 123
示例 - 想要:
#test search 123
#text to be commented out
#test 123
我可以通过 sed 做到这一点:
sed -i '/^#test search 123/!b; n; s/^/#/' test_file
但我想知道我是否能够在 python 中本地完成它。
最佳答案
import os
outfile = open('bla.txt.2', 'w')
search = "#test search 123"
flag = 0
with open('bla.txt', 'r') as f:
for line in f:
if flag == 1:
mod_line = "#" + line
outfile.write(mod_line)
flag = 0
continue
outfile.write(line)
if (search in line):
flag = 1
outfile.close()
os.remove('bla.txt')
os.rename('bla.txt.2', 'bla.txt')
关于Python 搜索字符串并替换下一行中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30936032/