我有一个像这样的文本文件
ababaabababab
+hostname R1
interface GigabitEthernet0/1
+shutdown
+banner login
-hostname r
ababababababa
ababaabababab
r#
我想得到类似这样的输出
>>> print running_conf
+hostname R1
interface GigabitEthernet0/1
+shutdown
+banner login
>>> print saved_conf
-hostname r
ababababababa
ababaabababab
在此网站上尝试了很多东西之后,我仍然无法使其正常工作。这是我的代码
with open ("file.text", "r") as saveoutput:
for line in saveoutput:
if line.startswith( '+' ):
continue
if line.startswith( '-' ):
break
print line
for line in saveoutput:
if line.startswith( '-' ):
if line.endswith( '#' ):
break
print line
答案 0 :(得分:1)
以下代码将输出文件中的所有内容,从以“ +”开头的行开始,直到到达以“-”开头的行为止。
copy = False
with open ("file.text", "r") as saveoutput:
for line in saveoutput:
if line.startswith( '+' ):
copy = True
if line.startswith( '-' ):
copy = False
if copy:
print line
和以下程序
copy = False
with open ("file.text", "r") as saveoutput:
for line in saveoutput:
if line.startswith( '-' ):
copy = True
if line.endswith( '#' ):
copy = False
if copy:
print line
将输出从以“-”开始的第一行到以“#”结束的行的所有内容。如果您希望有一个程序同时执行两个操作:
copy1 = False
copy2 = False
with open ("file.text", "r") as saveoutput:
for line in saveoutput:
if line.startswith( '+' ):
copy1 = True
if line.startswith( '-' ):
copy1 = False
if line.startswith( '-' ):
copy2 = True
if line.endswith( '#' ):
copy2 = False
if copy1 or copy2:
print line
答案 1 :(得分:0)
下面是提供所需输出的程序,尽管请清楚指定输出的情况。
flag=False
with open ("file.txt", "r") as saveoutput:
for line in saveoutput:
if line.startswith('-'):
flag=False
elif line.startswith('+'):
flag=True
if flag:
print(line,end='')
print('------------------------')
flag=False
with open ("file.txt", "r") as saveoutput:
for line in saveoutput:
if (line.startswith('+')) or (line.endswith('#\n')):
flag=False
elif line.startswith('-'):
flag=True
if flag:
print(line,end='')