当发现“Y”行时,如何删除“X”行

2024-04-16 21:07:01 发布

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

我有一个带有如下联系人的.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()

Tags: txtcomclose电子邮件emailcountline联系人
3条回答

这是我评论中一个未经测试的快速示例。通过在找到名称后从0开始计数,可以在找到匹配项后排除n行

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")

    delete_counter = float('inf')  # This can be any number above 2 to be honest
    for line in count_lineas:
        if line.strip("\n") == Y:
            delete_counter = 0     # Restart the counter
        if delete_counter > 2:     # Skip the next 2 lines too
            archivo1.write(line)   # Write the 3rd line onwards
        delete_counter += 1
    
    archivo1.close()

这不是最有效或最奇特的解决方案,它只是简单易懂的东西

这不是最好的解决方案,但一定要试一试

c.txt

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

编写此代码时假设每第三行就有一个新联系人

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

另一种方法是每三行评估一次,如下所示:

name = input("Enter the full name:")
with open("agenda.txt", "r") as f:
    lines = f.readlines()
with open("agenda.txt", "w") as f:
    for line_index in range(0, len(lines), 3):
        if lines[line_index].strip("\n") != name:
            f.write(lines[line_index])
            f.write(lines[line_index + 1])
            f.write(lines[line_index + 2])

这假定格式不变,并且.txt文件以“name”行开头

相关问题 更多 >