我有这篇文章,我将分享其中的一部分
ROMEO
But, soft! what light through yonder window breaks? It is the east, and Juliet is the sun.
JULIET
Ay me!
ROMEO
She speaks: O, speak again, bright angel! for thou art.
JULIET
O Romeo, Romeo! wherefore art thou Romeo? Deny thy father and refuse thy name;
ROMEO
Shall I hear more, or shall I speak at this?.
我想写一个循环,查找行中的名称,并将其后面的内容保存到特定文件中,在这种情况下,如果“ROMEO”是在每行之后找到的单词,它将保存到“ROMEO.txt”,直到找到“JULIET”为止,然后将所有内容保存到“JULIET.txt”。我试着自己用循环和if语句的合并来编写代码,但结果一无所获。 句柄=打开(“romeo full.txt”) 船长=“罗密欧”
handle = open("romeo-full.txt")
skipper = "ROMEO"
for line in handle:
line = line.strip()
while skipper == "ROMEO":
print(line) #This would be the write to file code
if line.startswith("ROMEO"):
skipper = "JULIET"
break
else:
continue
while skipper == "JULIET":
print(line) #This would be the write to file code
if line.startswith("ROMEO"):
skipper = "ROMEO"
break
else:
continue
输出基本上是“罗密欧”线循环,我知道它来自于通过第一行的while循环,但我想不出比这更接近我想要的
避免重复代码的一种方法是使用主文件中的头作为要写入的文件的“选择器”。比如:
try/except
块的目的是仅当我们遇到其中一个标题时才更改cur_file
(然后跳过它)避免这种情况的一种方法是使用dict的^{} 方法,并将
cur_file
作为默认值(因此它仅在头上更改):这里的缺点是每次头也会写入文件
您可以这样写入多个文件:
您应该始终使用
with
而不是open
和close
的原因是,如果出于某种原因您不关闭(如程序崩溃或忘记添加),文件将不会关闭,从而占用空间。我见过经常打开而不关闭的文件会导致服务器崩溃相关问题 更多 >
编程相关推荐