Python 2.7 Python在字符串匹配前后插入行
我在两个不同的行号上有两个变量Python 2.7 Python在字符串匹配前后插入行,python-2.7,Python 2.7,我在两个不同的行号上有两个变量var1和var2。我的任务是: 要打开输入文件,请搜索以var1开头的行,并在该行上方插入注释 要打开相同的输入文件,请搜索以var2开头的行,并在该行下方插入注释 我能达到1,但不是2 var1 = 2 #line number var2 = 5 #line number comment1 = "inserted text above var1" comment2 = "inserted text below var2" some for loop:
var1
和var2
。我的任务是:
var1
开头的行,并在该行上方插入注释var2
开头的行,并在该行下方插入注释var1 = 2 #line number
var2 = 5 #line number
comment1 = "inserted text above var1"
comment2 = "inserted text below var2"
some for loop:
found1 = False
found2 = False
for line in fileinput.input(source.txt, inplace=True):
if not found and line.startswith(var1):
print comment1
found1 = True
print line,
if not found and line.startswith(var2):
print line
found1 = True
print comment2,
输入文件:
1 abc
2 def
3 ghi
4 jkl
5 mno
6 pqr
7 stu
输出应为:
1 abc
inserted text above var1
2 def
3 ghi
4 jkl
5 mno
inserted text below var2
6 pqr
7 stu
你似乎有很多不需要的变量。按照我阅读代码的方式,基于缩进,您总是会打印comment2,有时还会打印一次以上的行。 循环不需要2个。您从未使用过found1或found2,并且从未定义找到的变量。这些变量可能是您不需要的。您要么需要将source.txt定义为变量,要么将其作为字符串传递(我认为您的意思是在其周围加上“),var1和var2可能也应该是字符串,因为str.startswith()需要传入字符串 把它简化一点,我想你不会有问题。假设你正确地处理了读取文件的过程,像这样的事情应该可以解决问题
var1= "2" #line number
var2 = "5" #line number
comment1 = "inserted text above var1"
comment2 = "inserted text below var2"
for line in fileinput.input("source.txt", inplace=True):
if line.startswith(var1):
print comment1
print line
if line.starswith(var2):
print comment2
谢谢..!很好..!我很高兴它对你有用。你介意把它标记为正确答案吗?