2 回答
TA贡献1725条经验 获得超7个赞
以下代码将从以“+”开头的行开始输出文件中的所有内容,直到到达以“-”开头的行:
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
TA贡献1773条经验 获得超3个赞
以下是提供所需输出的程序,但请清楚指定输出的情况。
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='')
添加回答
举报