如果满足不同的条件,是否有办法将文本写入不同的文件?

2024-05-19 21:38:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这篇文章,我将分享其中的一部分

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循环,但我想不出比这更接近我想要的


Tags: andthetxtforifislineskipper
2条回答

避免重复代码的一种方法是使用主文件中的头作为要写入的文件的“选择器”。比如:

with open("romeo-full.txt") as handle, \
     open("romeo.txt", 'w') as r_f, \
     open("juliet.txt", 'w') as j_f:

    file_chooser = {"ROMEO": r_f,
                    "JULIET": j_f}

    for line in handle:
        try:
            cur_file = file_chooser[line.strip()]
        except KeyError:     
            cur_file.write(line)

try/except块的目的是仅当我们遇到其中一个标题时才更改cur_file(然后跳过它)


避免这种情况的一种方法是使用dict的^{}方法,并将cur_file作为默认值(因此它仅在头上更改):

with open("romeo-full.txt") as handle, \
     open("romeo.txt", 'w') as r_f, \
     open("juliet.txt", 'w') as j_f:

    file_chooser = {"ROMEO": r_f,
                    "JULIET": j_f}
    cur_file = r_f
    for line in handle:
        cur_file = file_chooser.get(line.strip(), cur_file)

        cur_file.write(line)

这里的缺点是每次头也会写入文件

您可以这样写入多个文件:

with open('example1.txt', 'w') as file_1 \
        , open('example2.txt', 'w') as file_2 \
        , open('example3.txt', 'w') as file_3 \
        , open("romeo-full.txt", 'r') as handle:
    for line in handle:
        if condition_1:
            file_1.write(line)
        elif condition_2:
            file_2.write(line)
        elif condition_3:
            file_3.write(line)

您应该始终使用with而不是openclose的原因是,如果出于某种原因您不关闭(如程序崩溃或忘记添加),文件将不会关闭,从而占用空间。我见过经常打开而不关闭的文件会导致服务器崩溃

相关问题 更多 >