思路:

将内容读取后进行处理,将不要的那行数组列表的前、后加在一起,再写回txt文件中;

代码实现(只删一行):

主要文件 data.txt的内容

111
222
333
444
111
222
333
444

读取 data.txt 进行处理和写入

first_line = 0

count = 0   # 用于累加计算第几行数组

open_txt = open("data.txt", "r", encoding="utf-8")
read_txt = open_txt.readlines()     # 读取data.txt的所有内容
open_txt.close()

for content in read_txt:    # 循环判断内容是否存在
    if "222\n" not in content:
        count += 1      # 第 count 行不存在,count就+1成为下一行
    else:
        break       # 存在则退出循环

 # 数组列表机制是 min <= 内容 < max
 # 所以数组列表能从0开始,但是在 < max 时结束而不取到max
f_line = read_txt[first_line: count]
l_line = read_txt[count + 1:]

 # 将数组列表的前、后写回txt中
open_txt = open("data.txt", mode="w", encoding="utf-8")
open_txt.writelines(f_line + l_line)
open_txt.close()

处理后的data.txt

111
333
444
111
222
333
444

代码实现(删完为止):

读取data.txt进行处理和写入

first_line = 0

count = 0   # 用于累加计算第几行数组

open_txt = open("data.txt", "r", encoding="utf-8")
read_txt = open_txt.readlines()     # 读取data.txt的所有内容
open_txt.close()

for content in read_txt:    # 循环判断内容是否存在
    
    if "222\n" not in content:
        print(str(count) + ":" + content)     # 第 count 行不存在,count就+1成为下一行 
        count += 1
    elif "222\n" in content:    # 每当发现匹配,就将该行删掉,并更新循环的范围
        print(str(count) + ":" + content)
        f_line = read_txt[first_line: count]
        l_line = read_txt[count + 1:]
        read_txt = f_line + l_line      # 因为删掉了一行,数组列表少了一行,那么就不需要count+=1
    else:
        break       # 超出,退出
open_txt = open("data.txt", mode="w", encoding="utf-8")
open_txt.writelines(f_line + l_line)
open_txt.close()

处理后的data.txt

111
333
444
111
333
444