python - 找到“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()
解决方案
不完全是最好的解决方案,但一定要试一试。
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
推荐阅读
- yocto - Yocto Source Location 要定制?
- javascript - 在 react-native-maps 中显示标记的标注
- docker - Dockerfile 说 Copy failed: in .NET Core Dockerfile
- nunit-3.0 - Opencover - 命令行中的 NUnit3 没有结果
- c# - 并发读取和写入 Excel 文件
- javascript - 如何将更改时的列值映射到handsontable中的第1列值?
- javascript - 当为“var”和“let”分配一个引发错误的函数的返回值时,是什么导致了它们之间的不同行为
- java - 仅当表存在时如何从表中选择值
- c++ - MacOS 上 Qt GUI 小部件的异常大小
- mysql - 有没有办法将一个字符串拆分为多个字符串?