首页 > 解决方案 > 找到“Y”行时如何删除“X”行

问题描述

我有一个带有这样联系人的 .txt:

(第 1 行) Andrew
(第 2 行) andrew@email.com
(第 3 行) 314657463
(第 4 行) Ariana
(第 5 行) ariana@email.com
(第 6 行) 1026479657
(第 7 行) .
(第 n 行)...

(每个值在不同的行中)

我正在尝试编写代码(Python)来删除给定名称的 1 个完整联系人(姓名、电子邮件和电话号码)。

问题是,我无法删除电子邮件和电话号码。

这是我尝试过的:

def delete_someone():
    Y=input("Enter the full name:")
    archivo=open("agenda.txt", "r")
    count_lineas= archivo.readlines()
    archivo.close()
    archivo1= open("agenda.txt", "w")
    for line in count_lineas:
        if line.strip("\n")!= Y:
            archivo1.write(line)
    archivo1.close()

标签: python

解决方案


不完全是最好的解决方案,但一定要试一试。

c.txt

Andrew
andrew@email.com
314657463
Ariana
ariana@email.com
1026479657

编写此代码时假设新联系人从每 3 行开始。

x=open('c.txt','r')
test_list=[]
for y in x.readlines():
    #print(y.strip("\n"))
    test_list.append(y.strip("\n"))
while True:
    j=input("Enter a name to delete: ")
    if j in test_list:
        sd=test_list.index(j)
        for i in range(0,3):
            po=test_list.pop(sd)
        f=open('all.txt',"w")
        for j in test_list:
            f.write(j+"\n")
        print("File written successfully")
        break
    else:
        print("\nPlease enter the correct name...\n")

样品运行:

Enter a name to delete: Ariana
File written successfully

all.txt

Andrew
andrew@email.com
314657463

推荐阅读