首页 > 解决方案 > 如何检查是否在txt文件中的某个点之前找到了某行?

问题描述

我需要弄清楚在文本文件中出现另一个短语之前是否找到了某个短语/行。如果找到该短语,我将通过,如果它不存在,我将在截止点上方添加一行。值得注意的是,该短语也可能出现在文档的后面。

这种 txt 格式的示例可能是:

woijwoi

woeioasd
woaije
Is this found
owijefoiawjwfioj
This is the cutoff

asoi w
more text lines
Is this found
aoiw

搜索应该在“This is the cutoff”这个短语上截断。不知道截止将在哪条线上。如果在截止之前存在“Is this found”,则通过。如果没有,我想在输出文档的截止点上方添加短语“添加一行”。到目前为止我尝试过的代码示例,之前定义了所有字符串:

     find = 'Is this found'
     with open(longStr1) as old_file:
        lines = old_file.readlines()
        with open(endfile1, "w") as new_file:
            for num, line in enumerate(lines):
                if "This is the" in line:
                    base_num = num
                for num in range(1, base_num):
                    if not find in line:
                        if line.startswith("This is the"):
                        line = newbasecase + line 

我收到“未定义名称'base_num'”的错误是否有更好的方法来执行此搜索?

标签: python

解决方案


这样的事情呢?查找查找和截止索引位置,然后循环遍历行列表并检查截止索引,评估是否存在先前的“查找”变量,如果没有则添加“添加行”行并结束新文件。

find = "Is this found"
find_index = 0
cutoff = "This is the cutoff" 
cutoff_index = 0

with open(longStr1) as old_file:
    lines = old_file.readlines()
    if find in lines:
        find_index = lines.index(find)
    if cutoff in lines:
        cutoff_index = lines.index(cutoff)
    with open(endfile1, "w") as new_file:
        for num, line in enumerate(lines):
            if cutoff in line:
                if cutoff_index < find_index:
                    new_file.write("Adding a line\n")
                new_file.write(line)
                break
            new_file.write(line)

推荐阅读