如果我的代码混乱,我还有其他几条要补充。我正在尝试从文件中删除整个键,值。这些是带有键和值的字典格式。密钥是电子邮件,以便此人输入要删除的电子邮件。
我尝试使用pop和del,但是我做错了或者导致代码错误的
emailDict = dict()
initialQ = input("For E-mail's would you like to add, delete, lookup, or change? ")
if initialQ == "add":
with open("C:\\TestData\\EmailList.txt","a+") as infile:
howMany = int(input("How many people would you like to enter? "))
for x in range(howMany):
key = input("Please enter their E-mail: ")
value = input("Please enter name of who the E-mail belongs to: ")
infile.write(value+ " E-mail is ")
infile.write(key+"\n")
emailDict[key]= value
print("Please make sure info is correct",emailDict)
infile.close()
if initialQ == "delete":
with open("C:\\TestData\\EmailList.txt","r+") as infile:
howMany = int(input("How many people would you like to delete? "))
for x in range(howMany):
nameDel = input("Enter the email you would like to remove: ")
deleteP= infile.readlines()
if nameDel in deleteP:
del [key]
infile.close()
从文件中删除键和值。
答案 0 :(得分:0)
尝试这样的事情:
# read all the lines
with open("EmailList.txt") as infile:
deleteP= infile.readlines()
# if you have \n at the end, strip that
deleteP = [x.strip() for x in deleteP]
print(deleteP)
howMany = int(input("How many people would you like to delete? "))
for x in range(howMany):
nameDel = input("Enter the email you would like to remove: ")
if nameDel in deleteP:
deleteP.remove(nameDel)
print(deleteP)
示例文件
> cat EmailList.txt
abc@test.com
xyz@test.com
who@test.com
123@test.com
结果
['abc@test.com', 'xyz@test.com', 'who@test.com', '123@test.com']
How many people would you like to delete? 2
Enter the email you would like to remove: xyz@test.com
Enter the email you would like to remove: 123@test.com
['abc@test.com', 'who@test.com']
请注意,这不会将信息写回到文件中。您必须像这样将其自己写回到文件中:
with open("EmailList.txt", "w") as outfile:
for item in deleteP:
outfile.write(item + "\n")