我有一个文本文件,如下所示: 的 myFiles.txt
Dell 2015 A14523 Sam
Sony 2014 A74256 John
Acer 2018 A45656 Mark
Sony 2007 S12345 James
当我将索引作为输入时,我想删除数据,因此,我将文本文件转换为字典。通过这种方式,我得到了我的文本文件的索引。但是当我从字典中删除任何数据并将其余数据写入文本文件时,会发生键错误。 因为当我从字典中删除数据时,索引保持不变 例如: 我为不同的密钥创建了4行,即1,2,3和4 当我从索引2中删除数据时,字典索引保持不变,我留下1,3和4,当我将数据重写为文本文件时,它将给出关键错误。 如何从文本文件中删除数据。 我是python的新手。帮我解决一下
def deleteFunction(self):
ownerListDic = {}
num = 1
with open("myFiles.txt", "r") as oy:
for line in oy:
li = line.strip().split()
ownerListDic[num] = {"name": li[0], "purchase": li[
1], "bluePlate": li[2], "owner": li[3]}
num += 1
# enter the record id to delete from the text file
indexId = int(input("Enter record ID: "))
if indexId in ownerListDic:
# prompting to confirm the user you are going to delete
# this data
print(("You arev about to delete " + ''.join(ownerListDic[indexId]['name'] +
" " + ownerListDic[indexId]['purchase'] + " " + ownerListDic[indexId]["bluePlate"] + " " + ownerListDic[indexId]['owner'])) + " .")
# ask user to delete the data
delete = input(
"Do you wish to delete this record (Y/N): ").upper()
# if yes then data will delete
if delete == "Y":
ownerListDic.pop(indexId, None)
num=1
with open("myFiles.txt", 'w') as log:
for dataValue in ownerListDic.values():
log.write(ownerListDic[num]['name'] +
"\t" + ownerListDic[num]['purchase'] + "\t" + ownerListDic[num]["bluePlate"] + "\t" + ownerListDic[num]['owner'] + "\n")
num += 1
# after deletion this message will print
print("Record deleted.")