我有一个文本文件,想要在 Windows 上使用 Python 3.5 打印另外两行之间的行。我想将戏剧中的人物打印到另一个文件中。文本文件如下所示:
...
Characters:
Peter, the king.
Anna, court lady.
Michael, caretaker.
Andre, soldier.
Tina, baker.
First scene.
...
我想打印“角色:”和“第一个场景”行之间的所有角色名称。我的第一次尝试是:
newfile = open('newfile.txt', 'w')
with open('drama.txt', 'r') as f:
for line in f:
if line.startswith('Characters:'):
print(next(f), file = newfile)
但这只打印一行,我需要几行,并且使用 next() 函数进行迭代在打印一行后总是导致 StopIteration 错误。 那么有没有办法说:打印“字符:”行和“第一个场景”行之间的所有行?使用索引实际上是不可能的,因为我正在为几部戏剧做这件事,而且它们都有不同数量的角色。
最佳答案
您可以设置一个 bool 值来知道是否打印一行:
newfile = open('newfile.txt', 'w')
printing = False
with open('drama.txt', 'r') as f:
for line in f:
if line.startswith('Characters:'):
printing = True
continue # go to next line
elif line.startswith('First scene'):
printing = False
break # quit file reading
if printing:
print(line, file=newfile)
newfile.close()
关于python - 从文本文件中打印两个特定行(关键字)之间的多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49223576/