【发布时间】:2021-12-26 15:18:15
【问题描述】:
这是我编写的示例代码,用于测试更新客户详细信息的逻辑。我想输入新客户详细信息,然后用新详细信息替换旧值。这是针对银行服务系统的,这是我坚持的最后一部分。如果有人有任何基本解决方案,我相信我可以在我的代码中实现它。
我只需要一种方法来更新文件中的 2D 列表而不覆盖它。
附加信息:
我不允许使用额外的库..只有 datetime 和 os
我应该在模块化编程中编码
def main():
def info():
details = []
name = input('Enter your first name')
name2 = input('Enter your second name')
age = input('Enter your age')
details.append(name)
details.append(name2)
details.append(age)
return details
def filewrite(ClientDetails):
#read and evaluate the list in the file
clientFile = open('Details.txt','r')
tempList = eval(clientFile.read())
clientFile.close()
tempList.append(ClientDetails)
clientFile = open('Details.txt','w')
clientFile.write(str(tempList))
clientFile.close()
ClientDetails = info()
filewrite(ClientDetails)
def search():
clientFile = open('Details.txt','r')
readList1 = eval(clientFile.read())
clientFile.close()
adminName = input('Enter your name:')
for i in range(len(readList1)):
for j in range(len(readList1)):
if adminName == readList1[i][0]:
value = True
mylist = readList1[i]
Sname = readList1[i][1]
print(mylist)
print(Sname)
update = input('Enter the updated value')
with open('Details.txt','w+') as a:
readList[i][0] = str(update)
search()
main()
【问题讨论】:
-
不要在每次迭代时都以读取模式打开文件,而是将循环放在上下文管理器中,也不建议真正使用
eval,最好使用ast.literal_eval,但是当你不能使用导入,只是不要将文件中的数据存储为列表,而是存储在由分号或逗号分隔的行和列中 -
如果我将它们保存为行和列,我仍然可以通过输入客户姓名来访问数据吗?是否更容易更新
-
我可以把 eval 替换为 'ast.literal_eval'
-
更新是一样的,但是对于人类来说更容易读取原始文件并且由于不评估任何东西而更安全,如果你想要更容易更新你需要使用
json或一些数据库,是的,你应该能够简单地将eval替换为ast.literal_eval(你需要先import ast) -
哦,我们不允许导入 ast 也不允许使用 JSON。它有非常严格的指导方针
标签: python python-3.x banking