python - 从文本文件中打印两个特定行(关键字)之间的多行

标签 python python-3.x printing text-files lines

我有一个文本文件,想要在 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/

相关文章:

python - 如何在 open cv python 中从特定帧播放视频和音频?

javascript - {{ oauth_token }} 在源中显示并工作,但不在页面上

arrays - Matrix/2D-numpy 数组中的着色条目?

python - 在 Python 中使用 print 作为类方法名

html to excel - 在每一页上打印第 1 行

python - numpy - 如何外部连接数组

python-3.x - python |以时间间隔从网络摄像头捕获图像

python - 重新findall : Inserting a variable value in regex failing when {} already used for range of occurences to match

javascript - 从 Javascript 打印图像

python - 为什么QThread对象在创建worker QObject时没有完成信号?