python - 将第一段从 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
解决方案
假设段落由空行分隔,您可以逐行迭代文件并将它们写入新文件,直到到达空行。可以使用以下命令发现空行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)
推荐阅读
- java - 将 ArrayList 折叠为单个整数
- python - 将字典插入字典的排序列表
- android - 如何从默认资源以编程方式设置单选按钮的背景
- spring - 使用 Spring Boot 连接到 MongoDb
- flutter - 将嵌套地图转换为 json 以进行修补
- python - 在两个下拉列表之间解析
- c - Get_next_line : 在 Mac 上 BUFFER_SIZE 介于 8 和 15 之间时中止
- blazor - 从托管解决方案中的 Blazor WebAssembly 导航到服务器页面
- laravel - 雄辩的聚合体
- javascript - 当对象属性值被更改时,Angular 将样式更新为 ngFor 中的 div