首页 > 解决方案 > 将第一段从 infile 打印到 outfile

问题描述

我有一个包含演讲的文件,并且有一个空的输出文件。我正在尝试打印演讲的第一段(读取 infile)并使用 if/else 语句将其打印到 outfile 中。

该程序没有窃听,但它没有输出到我的输出文件。

file = open("/Users/newuser/Desktop/MLKspeech.txt", "r")
file2 = open("/Users/newuser/Desktop/mlkparagraph.txt", "w")

content = file.read()
for j in content:
    if (j == ""):
        continue
    elif (j == "\n"):
        file2.write(content)
   else:
       break

标签: python

解决方案


假设段落由空行分隔,您可以逐行迭代文件并将它们写入新文件,直到到达空行。可以使用以下命令发现空行str.isspace()

with open("MLKspeech.txt") as in_file, open("mlkparagraph.txt", 'w') as out_file:
    for line in in_file:
        if line.isspace():
            break
        out_file.write(line)

推荐阅读